﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：ExWarehousingImpl
// 文件功能描述：出库任务生成
//
// 创建者：名字 (zzl)
// 时间：2021/12/21 15:38:43
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion




using KingerRobot.MexicoSailunMDC.Dao;
using KingerRobot.MexicoSailunMDC.SpiService.Managers;
using KingerRobot.MexicoSailunMES.Spi;
using KingerRobot.MexicoSailunMES.Spi.DTO;
using System;

//using KingerRobot.MexicoSailunMES.Dao;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace KingerRobot.MexicoSailunMDC.SpiService;
[Logging]
public class WarehousingOutImpl : IWarehousingOutService
{
    private readonly static ITask _Task = new BTask();
    private readonly static ITaskCmd _TaskCmd = new BTaskCmd();
    private readonly static IRcsEquipCuringDitch _RcsEquipCuringDitch = new BRcsEquipCuringDitch();
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();
    private readonly static IWmsOutOrderMaster _WmsOutOrderMaster = new BWmsOutOrderMaster();
    private readonly static IWcsAsrsNetOutPut _WcsAsrsNetOutPut = new BWcsAsrsNetOutPut();
    private readonly static IWcsAsrsCrnOutPut _WcsAsrsCrnOutPut = new BWcsAsrsCrnOutPut();
    private readonly static IRcsEquipCrn _RcsEquipCrn = new BRcsEquipCrn();
    private readonly static IRcsLocation _RcsLocation = new BRcsLocation();
    private readonly static IWmsSetting _WmsSetting = new BWmsSetting();
    private readonly static IWcsAsrsLocHalt _WcsAsrsLocHalt = new BWcsAsrsLocHalt();
    private readonly static IWarehousOut _WarehousOut = new BWarehousOut();
    private readonly static IPositionService _PositionService = new PositionImpl();
    private readonly static IProdProduct _ProdProduct = new BProdProduct();
    private readonly static IWcsEquipLocHold _WcsEquipLocHold = new BWcsEquipLocHold();
    private readonly static IProdMaterial _ProdMaterial = new BProdMaterial();
    private readonly static IWms2MesService _Wms2MesService = new Wms2MesImpl();
    private readonly static IRcsEquipCuring _RcsEquipCuring = new BRcsEquipCuring();
    private readonly static IWcsAsrsCrnAbnormalOutPut _WcsAsrsCrnAbnormalOutPut = new BWcsAsrsCrnAbnormalOutPut();
    private readonly static IWcsLocSku _WcsLocSku = new BWcsLocSku();
    private readonly static IWcsNetAbnormal _WcsNetAbnormal = new BWcsNetAbnormal();
    private readonly static IMonitor _monitor = new BMonitor();
    private readonly static IWcsOutputLog _WcsOutputLog = new BWcsOutputLog();
    private readonly static IWmsPriorityCuring _WmsPriorityCuring = new BWmsPriorityCuring();
    private readonly static IWcsAsrsCrnInput _WcsAsrsCrnInput = new BWcsAsrsCrnInput();
    private static ConcurrentDictionary<string, DateTime?> cache = new ConcurrentDictionary<string, DateTime?>();
    private readonly static IPOTcmGtReqRepositories _tcmGtReqRepositories = new POTcmGtReqRepositories();
    private readonly static IPOTcmGtSpecRepositories _tcmGtSpecRepositories = new POTcmGtSpecRepositories();
    /// <summary>
    /// 1、双模请料，单胎出库
    /// 2、双模请料，不同堆垛机出库
    /// </summary>
    public void CreateTask()
    {
        // 获取所有堆垛机[任务、异常]，IsEnable 为：True 可用
        var crnForks = _RcsEquipCrn.GetUsableCrnFork();
        var crnIds = crnForks.Where(t => t.IsEnable == true)
            .Select(t => t.CrnId)
            .Distinct()
            .ToList(); // 有效堆垛机ID
        if (!crnIds.Any())
        {
            return;
        }
        //////WriteLog($"CreateTask-111", true);

        //按库位 创建出库订单
        var orderSummaryGroupiesLoc = _WmsOutOrderSummary.GetNoTaskLocOrderSummaryGroup((int)EnumCodeOutOrderType.WarehouseLocation);
        //////WriteLog($"CreateTask-444", true);
        if (orderSummaryGroupiesLoc.Any())
        {
            foreach (var master in orderSummaryGroupiesLoc)
            {
                try
                {
                    _WarehousOut.CreateTaskByLocOrders(master, crnForks);
                }
                catch (Exception ex)
                {
                    //WriteLog($"库位出库异常：{ex.Message}", true);
                }
            }
        }

        //////WriteLog($"CreateTask-555", true);
        ////WriteLog($"出库111676", true);
        // 按条码，创建出库订单
        //TODO增加按条码请料创建出库任务 目标位是硫化机
        var orderSummaryGroupiesProductCode = _WmsOutOrderSummary.GetNoTaskOrderSummaryGroup((int)EnumCodeOutOrderType.WarehouseProductCode);
        //////WriteLog($"CreateTask-666", true);
        if (orderSummaryGroupiesProductCode.Any())
        {
            foreach (var master in orderSummaryGroupiesProductCode)
            {
                try
                {
                    _WarehousOut.CreateTaskByProductCodeOrders(master, crnForks);
                }
                catch (Exception ex)
                {
                    //WriteLog($"按条码请料出库异常：{ex.Message}", true);
                }
            }
        }
        //////WriteLog($"CreateTask-777", true);

        //按硫化机请料创建出库任务（中间表）
        var summaryGroups = Task.Run(() =>
        {
            // 所有未创建任务的请料订单（优先级、时间排序）
            return _WmsOutOrderSummary.GetNoTaskOrderSummaryGroup((int)EnumCodeOutOrderType.RequesMaterial);
        });

        //按规格请料创建出库任务（规格、数量）
        var summaryGroupsMaterial = Task.Run(() =>
        {
            // 所有未创建任务的请料订单（优先级、时间排序）
            return _WmsOutOrderSummary.GetNoTaskOrderSummaryGroup((int)EnumCodeOutOrderType.WarehouseMaterial);
        });

        //所有货位信息 test
        var locs = Task.Run(_RcsLocation.GetAllNoHaveHighLocationsISLoc);

        var products = Task.Run(_ProdProduct.GetWarehousingOutProduct);

        var outInfoBeans = Task.Run(() =>
        {
            // 堆垛机负责有货货位，出库路线（路线、货叉可用数量、货叉信息）
            return _WcsAsrsNetOutPut.GetAsrsNetOutputByForkInfo(crnForks);
        });


        var platforms = Task.Run(() =>
        {
            // 出库站台位（所有站台为）
            //【已解决】改成获取出库所有站台位（堆垛机出库站台---区域、堆垛机、（序号、库位））
            return _WcsAsrsCrnOutPut.GetAllOutLoc(crnIds);
        });

        var wcsAsrsLocs = Task.Run(_WcsAsrsLocHalt.GetAsrsLocHalt);

        var wcsEquipLocs = Task.Run(_WcsEquipLocHold.GetEquipLocHolds);
        //WriteLog($"CreateTask-888", true);

        var list = summaryGroups.Result.Concat(summaryGroupsMaterial.Result);
        if (!list.Any()) return;
        //////WriteLog($"CreateTask-999", true);
        // 创建任务优先级 先订单优先级优先，再时间优先
        var orderSummaryGroupies = list.OrderBy(t => t.OrderPriority).ThenBy(t => t.CreateTime).ToList();
        if (!orderSummaryGroupies.Any())
        {
            //WriteLog($"出库 请料订单数量：{orderSummaryGroupies.Count}", true);
            return;
        }

        // 出库任务排序
        var newSummary = new List<OrderSummaryGroupyMaster>();
        OderSummary(orderSummaryGroupies, ref newSummary);
        orderSummaryGroupies = newSummary;
        //堆垛机负责有货货位，出库路线（路线、货叉可用数量、货叉信息）
        var asrsOutInfoBeans = outInfoBeans.Result;
        //WriteLog($"CreateTask-1222", true);
        if (!asrsOutInfoBeans.Any())
        {
            //WriteLog($"出库 路线 总数：{asrsOutInfoBeans.Count}", true);
            return;
        }
        //WriteLog($"出库111770", true);
        //获取出库所有站台位（堆垛机出库站台---区域、堆垛机、（序号、库位））
        var platformLocs = platforms.Result;
        //WriteLog($"CreateTask-1333", true);
        if (!platformLocs.Any())
        {
            //WriteLog($"出库 站台位 总数：{platformLocs.Count}", true);
            return;
        }
        // 所有停机货位
        var wcsAsrsLocHalts = wcsAsrsLocs.Result;

        //查询可用出库产品（质量N；非冻结）
        var productN = products.Result;
        //所有货位信息
        var rcsLocations = locs.Result;

        // 可用（非禁用、入库缓存非0）堆垛机管理货位
        var useCrnId = platformLocs.Select(t => t.CrnId).ToList();
        var wcsEquipLocHolds = wcsEquipLocs.Result.Where(t => useCrnId.Contains(t.EquipId)).ToList();

     // //WriteLog($"16号出库路线{wcsEquipLocHolds.Where(t => t.EquipId == 10031601).Select(t=>t.Id).ToJson()}",true);
        productN = productN.Join(rcsLocations, f => f.LocId, s => s.Id, (f, s) => new ProductLocBean
        {
            LocId = f.LocId,
            SkuId = f.SkuId,
            GroupIndex = s.GroupIndex,
            MaterialId = s.MaterialId,
            POProdSkuProduct = f.POProdSkuProduct,
            POProdProduct = f.POProdProduct,
        }).Join(wcsEquipLocHolds, f => f.LocId, s => s.LocId, (f, s) => new ProductLocBean
        {
            LocId = f.LocId,
            GroupIndex = f.GroupIndex,
            SkuId = f.SkuId,
            MaterialId = f.MaterialId,
            CrnId = s.EquipId,
            POProdSkuProduct = f.POProdSkuProduct,
            POProdProduct = f.POProdProduct,

        }).ToList();
        ////WriteLog($"16号出库路线{productN.Where(t => t.EquipId == 10031601).ToJson()}", true);
        //WriteLog($"CreateTask-1777", true);

        var wmsSettingCall = _WmsSetting.GetWmsSettingByCode(ConstFields.CallCuringTimeOut);
        _ = int.TryParse(wmsSettingCall?.Value, out var second);
        var haltLocs = wcsAsrsLocHalts.Select(t => t.LocId);

        List<long> NoMaterialIdList = new List<long>();

        // 物料
        var materialGroupCount = rcsLocations.GroupBy(t => t.MaterialId.GetValueOrDefault()).Select(t => new
        {
            MaterialId = t.Key,
            Count = t.Count(),
        }).ToList();

        //开始循环出库订单
        foreach (var master in orderSummaryGroupies)
        {
            //WriteLog($"StartMaster,{master.MasterId}-111", true);
            var summaryMaterials = master.POWmsOutOrderSummaries.GroupBy(t => t.MaterialId)
                .Select(t => new { materialId = t.Key, Count = t.Count() })
                 .ToList();
            //证明是单一物料 
            if (summaryMaterials.Count == 1)
            {
                var summaryMaterialId = summaryMaterials[0].materialId;
                var hasCount = NoMaterialIdList.Where(t => t == summaryMaterialId).Count();
                var mmc = materialGroupCount.Where(t => t.MaterialId == summaryMaterialId).FirstOrDefault()?.Count ?? 0;
                if (hasCount > 0 || mmc == 0)
                {
                    var materialCode = _ProdMaterial.GetMaterialById(summaryMaterialId ?? 0)?.MaterialCode;


                    var ids = master.POWmsOutOrderSummaries.Select(t => t.Id ?? 0).ToList();
                    // var materialCode = _ProdMaterial.GetMaterialById(summaryMaterialId ?? 0)?.MaterialCode;
                    _WmsOutOrderSummary.UpdateOrderSummaryRemark(ids, $"物料编号{materialCode} 库存不足。");
                    _WmsOutOrderMaster.UpdateMasterOrderPriority(master.MasterId, -1);
                    continue;
                }
            }
            //WriteLog($"StartMaster,{master.MasterId}-222", true);
            // 判断是否有配对胎（second = 0 不等待，直接出库）
            //一个主表只有一个从表的情况 暂时跳出
            if (master.Count == 1 && second > 0)
            {
                continue;
                //WriteLog($"StartMaster,等待配对,{master.MasterId}-111", true);
                // 有双胎任务
                if (orderSummaryGroupies.Where(t => t.Count > 1).Any())
                {
                    //WriteLog($"出库111823", true);
                    // 单胎订单是否有配对
                    var targetLoc = master.POWmsOutOrderSummaries.FirstOrDefault()?.TargetLoc ?? 0;
                    var summaryFlag = _WmsOutOrderSummary.IsOutOrderSummaryPairByLocId(targetLoc);
                    //WriteLog($"StartMaster,等待配对,{master.MasterId}-222", true);
                    if (!summaryFlag)
                    {
                        //WriteLog($"出库111829", true);
                        // 是否超时
                        DateTime dateTime = DateTime.Now;
                        TimeSpan ts = dateTime.Subtract(master.CreateTime.GetValueOrDefault());
                        //WriteLog($"出库1113332", true);
                        var total = ts.TotalSeconds;
                        if (total < second)
                        {
                            //WriteLog($"出库1118372", true);
                            var newDate = DateTime.Now;
                            var summaryids = master.POWmsOutOrderSummaries.Select(t => t.Id.GetValueOrDefault()).ToList();
                            _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"单胎任务等待{second}秒,还差{second - total}秒{newDate}");
                            //WriteLog($"StartMaster,结束配对,{master.MasterId}", true);
                            continue;
                        }
                    }
                }
            }

            // 硫化机，可选择路线 0ns
            // 区域——堆垛机——路线分数——目标硫化位1
            // 区域——堆垛机——路线分数——目标硫化位2
            //WriteLog($"StartMaster,{master.MasterId}-333", true);
            var asrsNetOutputs = IsNetOutBySummaryTarget(master, asrsOutInfoBeans);
            //WriteLog($"StartMaster,{master.MasterId}-444", true);
            if (!asrsNetOutputs.Any())
            {
                // 没有可选路线（原因：生成一个任务会删除一条出库路线，最终可能找不到出库路线），重新查找所有可用出库路线
                //WriteLog($"出库111857", true);
                asrsOutInfoBeans = _WcsAsrsNetOutPut.GetAsrsNetOutputByForkInfo(crnForks);
                asrsNetOutputs = IsNetOutBySummaryTarget(master, asrsOutInfoBeans);
                //WriteLog($"出库111860", true);
                if (!asrsNetOutputs.Any())
                {
                    var newDate = DateTime.Now;
                    var summaryids = master.POWmsOutOrderSummaries.Select(t => t.Id.GetValueOrDefault()).ToList();
                    _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"出库订单没有可选路线,一个循环内每个堆垛机已经生成一个任务{newDate}");
                    continue;
                }
                //WriteLog($"出库111868", true);
            }
            //WriteLog($"StartMaster,{master.MasterId}-555", true);

            // 判断库存
            var materialCount = master.POWmsOutOrderSummaries.GroupBy(t => t.MaterialId).Select(t => new
            {
                MaterialId = t.Key.Value,
                Count = t.Sum(t => t.PlanCount - t.RealCount),
            }).ToList();
            var isMaterialId = 0L;
            //WriteLog($"StartMaster,{master.MasterId}-666", true);
            foreach (var material in materialCount)
            {
                List<ProductLocBean> pMaterial = new List<ProductLocBean>();

                ////在此处判断此请料单硫化机是否指定物料生产时间
                //var summariesCuringLocs = master.POWmsOutOrderSummaries.Select(t => t.TargetLoc ?? 0).ToList();
                //var priorityCurings = _WmsPriorityCuring.GetWmsPriorityCuringsByLocIds(summariesCuringLocs);
                ////如果此请料单的硫化机制定了生产时间 则在可用物料处进行筛选
                //if (priorityCurings is not null && priorityCurings.Any())
                //{
                //    var priorityCuring = priorityCurings.FirstOrDefault();
                //    var startTime = priorityCuring.StartTime;
                //    var endTime = priorityCuring.EndTime;
                //    pMaterial = productN.Where(t => t.MaterialId == material.MaterialId && t.POProdProduct.MdTime >= startTime && t.POProdProduct.MdTime < endTime)
                //   .GroupBy(c => new { c.SkuId, c.CrnId, c.LocId, c.GroupIndex, c.MaterialId, c.POProdProduct, c.POProdSkuProduct })
                //   .Select(c => c.FirstOrDefault()).ToList();
                //    //如果找到的指定时间物料数小于请料单数 则再去找所有物料
                //    // if (pMaterial.Count < master.POWmsOutOrderSummaries.Count) 
                //    // {
                //    //     pMaterial = productN.Where(t => t.MaterialId == material.MaterialId)
                //    //.GroupBy(c => new { c.SkuId, c.CrnId, c.LocId, c.GroupIndex, c.MaterialId, c.POProdProduct, c.POProdSkuProduct })
                //    //.Select(c => c.FirstOrDefault()).ToList();
                //    // }
                //    if (pMaterial.Count == 0)
                //    {
                //        pMaterial = productN.Where(t => t.MaterialId == material.MaterialId)
                //   .GroupBy(c => new { c.SkuId, c.CrnId, c.LocId, c.GroupIndex, c.MaterialId, c.POProdProduct, c.POProdSkuProduct })
                //   .Select(c => c.FirstOrDefault()).ToList();
                //    }
                //}
                //else
                //{
                //   pMaterial = productN.Where(t => t.MaterialId == material.MaterialId)
                //.GroupBy(c => new { c.SkuId, c.CrnId, c.LocId, c.GroupIndex, c.MaterialId, c.POProdProduct, c.POProdSkuProduct })
                //.Select(c => c.FirstOrDefault()).ToList();
                //}

                pMaterial = productN.Where(t => t.MaterialId == material.MaterialId)
         .GroupBy(c => new { c.SkuId, c.CrnId, c.LocId, c.GroupIndex, c.MaterialId, c.POProdProduct, c.POProdSkuProduct })
         .Select(c => c.FirstOrDefault()).ToList();



                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-2232", true);
                // 堆垛机物料数量
                var pMaterialGroup = pMaterial.GroupBy(t => t.CrnId).Select(t => new
                {
                    CrnId = t.Key.Value,
                    Count = t.Count()
                }).ToList();
                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-333", true);
                if (pMaterialGroup.Count == 0)
                {
                    // 堆垛机不满足
                    isMaterialId = material.MaterialId;
                    //break;
                    continue;
                }
                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-444", true);
                // 满足数量堆垛机
                var materCrnIds = pMaterialGroup.Where(t => t.Count >= 2 && t.Count >= material.Count).Select(t => t.CrnId).ToList();
                var flag = materCrnIds.Any();
                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-555", true);
                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-666", true);
                // 相同物料，已经拆单数量
                var summaryCount = 0;

                //                if (!flag)
                //                {
                //                    summaryCount = _WmsOutOrderSummary.GetOutOrderSummaryNoTaskList(new int?[] { (int)EnumCodeOutOrderType.RequesMaterial, (int)EnumCodeOutOrderType.WarehouseMaterial })
                //.Where(t => t.MaterialId == material.MaterialId && t.SplitMasterid != null && t.StartLoc is null)
                //.Count();
                //                }
                _ = decimal.TryParse(_WmsSetting.GetWmsSettingByCode(ConstFields.SpiltOrder).Value, out var splitOrder);
                //物料数<请料数时 拆分订单(暂时不拆分订单 注释)
                if (!flag)
                {
                    isMaterialId = material.MaterialId;
                    //    //if (splitOrder == 1)
                    //    //{
                    //    summaryCount = _WmsOutOrderSummary.GetOutOrderSummaryNoTaskList(new int?[] { (int)EnumCodeOutOrderType.RequesMaterial, (int)EnumCodeOutOrderType.WarehouseMaterial })
                    //.Where(t => t.MaterialId == material.MaterialId && t.SplitMasterid != null && t.StartLoc is null).Count();

                    //    //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-888", true);
                    //    if (material.Count > 1 && pMaterialGroup.Count >= 1 && summaryCount == 0)
                    //    {

                    //        //_ = decimal.TryParse(_WmsSetting.GetWmsSettingByCode(ConstFields.SpiltOrder).Value, out var splitOrder);
                    //        //WriteLog($"拆分订单setting{splitOrder}", true);
                    //        if (splitOrder == 1)
                    //        {
                    //            var newDate = DateTime.Now;
                    //            var summaryids = master.POWmsOutOrderSummaries.Select(t => t.Id.GetValueOrDefault()).ToList();
                    //            //var prodMaterial = _ProdMaterial.GetMaterialById(material.MaterialId);
                    //            //var spec = prodMaterial?.Spec;
                    //            _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"单个堆垛机物料{material.MaterialId}库存不足{newDate}拆分订单1,原masterId{master.MasterId}");
                    //            SplitOrder(master);
                    //            isMaterialId = -1;
                    //            //WriteLog($"单个堆垛机物料{material.MaterialId}库存不足{newDate}拆分订单1,原masterId{master.MasterId}", true);
                    //            ////break;
                    //            continue;
                    //        }
                    //        else
                    //        {
                    //            continue;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //continue;
                    //        //// 堆垛机不满足
                    //        isMaterialId = material.MaterialId;
                    //        //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-1010", true);
                    //        break;
                    //    }
                    //    //}
                    //    //else
                    //    //{
                    //    //    continue;
                    //    //}

                }
                else  // 堆垛机(物料数)满足
                {

                    if (material.Count > 1)
                    {
                        //1.得到所有停机货位 2.得到满足物料数量的堆垛机 3.得到满足数量的堆垛机管理的货位去掉停机货位之后的货位数量 如果为0说明满足库位数量的都在停机货位下
                        var pMaterialNotHalt = new List<ProductLocBean>();
                        //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-111940", true);
                        // pMaterial.Where(t => !haltLocs.Contains(t.LocId) && materCrnIds.Contains(t.CrnId.GetValueOrDefault())).ToList();
                        foreach (var crnId in materCrnIds)
                        {
                            //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-1119432", true);
                            //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-CRN{crnId}", true);
                            var crnLocs = pMaterial.Where(t => t.CrnId == crnId).ToList();
                            //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-CRN{crnId},-crnLocs{crnLocs.Count}-1119433", true);
                            var crnGroupIndex = crnLocs.GroupBy(t => t.GroupIndex).Count(); // 判断是否存在不同序号库位
                            if (crnGroupIndex == 1)
                            {

                                // 同一方向库位
                                crnLocs = crnLocs.Where(t => !haltLocs.Contains(t.LocId)).ToList();
                                pMaterialNotHalt.AddRange(crnLocs);
                                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-CRN{crnId},-crnLocs{crnLocs.Count}-1119434", true);
                            }
                            else
                            {

                                // 不同方向库位
                                pMaterialNotHalt.AddRange(crnLocs);
                                //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-CRN{crnId},-crnLocs{crnLocs.Count}-1119435", true);
                            }
                        }
                        //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-{pMaterialNotHalt.ToJson()}-1119436", true);
                        pMaterialGroup = pMaterialNotHalt.GroupBy(t => t.CrnId).Select(t => new
                        {
                            CrnId = t.Key.Value,
                            Count = t.Count()
                        }).ToList();
                        //WriteLog($"StartMaterial,{master.MasterId},{pMaterialGroup.ToJson()},material.Count{material.Count}-1119437", true);
                        materCrnIds = pMaterialGroup.Where(t => t.Count >= 2 && t.Count >= material.Count).Select(t => t.CrnId).ToList();
                        flag = materCrnIds.Any();
                        if (!flag)
                        {
                            //WriteLog($"StartMaterial,{master.MasterId},{material.MaterialId}-1119444", true);
                            isMaterialId = material.MaterialId;
                            //if (splitOrder == 1)
                            //{
                            //    if (summaryCount == 0)
                            //    {
                            //        var newDate = DateTime.Now;
                            //        var summaryids = master.POWmsOutOrderSummaries.Select(t => t.Id.GetValueOrDefault()).ToList();
                            //        // var spec = prodMaterial?.Spec;
                            //        _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"单个堆垛机物料{material.MaterialId}都在停机货位{newDate}拆分订单2,原masterId{master.MasterId}");
                            //        SplitOrder(master);
                            //        isMaterialId = -1;
                            //        //WriteLog($"单个堆垛机物料{material.MaterialId}都在停机货位{newDate}拆分订单2,原masterId{master.MasterId}", true);
                            //        break;
                            //    }
                            //    else
                            //    {
                            //        isMaterialId = material.MaterialId;
                            //        break;
                            //    }
                            //}
                            //else
                            //{
                            //    continue;
                            //}
                        }
                    }
                }
            }

            if (isMaterialId == -1)
            {
                continue;
            }
            if (isMaterialId > 0)
            {
                var materialCode = _ProdMaterial.GetMaterialById(isMaterialId)?.MaterialCode;
                //WriteLog($"StartMaterial,{master.MasterId},-1111008", true);
                var newDate = DateTime.Now;
                var summaryids = master.POWmsOutOrderSummaries.Select(t => t.Id.GetValueOrDefault()).ToList();
                // var prodMaterial = _ProdMaterial.GetMaterialById(isMaterialId);
                // var spec = prodMaterial?.Spec;
                //WriteLog($"StartMaterial,{master.MasterId},1111013", true);
                _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"物料编号{materialCode} 库存不足");
                _WmsOutOrderMaster.UpdateMasterOrderPriority(master.MasterId, -1);
                NoMaterialIdList.Add(isMaterialId);
                continue;
            }
            //WriteLog($"StartMaster,{master.MasterId}-888", true);




            //// region 这一块新增 
            ////在此处判断此请料单硫化机是否制定物料生产时间
            //var newSummariesCuringLocs = master.POWmsOutOrderSummaries.Select(t => t.TargetLoc ?? 0).ToList();
            //var newPriorityCurings = _WmsPriorityCuring.GetWmsPriorityCuringsByLocIds(newSummariesCuringLocs);
            ////如果此请料单的硫化机制定了生产时间 则在可用物料处进行筛选
            //if (newPriorityCurings is not null && newPriorityCurings.Any())
            //{
            //    var priorityCuring = newPriorityCurings.FirstOrDefault();
            //    var startTime = priorityCuring.StartTime;
            //    var endTime = priorityCuring.EndTime;
            //    var materialId = master.POWmsOutOrderSummaries[0]?.MaterialId ?? 0;

            //    var productN1 = new List<ProductLocBean>();
            //    productN1 = productN.Where(t => t.POProdProduct.MdTime >= startTime && t.POProdProduct.MdTime < endTime && t.MaterialId == materialId).ToList();
            //    //此处可能有问题
            //    if (productN1.Count >= master.POWmsOutOrderSummaries.Count)
            //    {
            //        productN = productN1;
            //    }
            //    //WriteLog($"硫化主订单{master.MasterId}时间:{startTime},库存数{productN1.Count},订单数{master.Count}", true);
            //    //WriteLog($"硫化主订单{master.MasterId}时间:{startTime}-{endTime},开始位置{master.POWmsOutOrderSummaries[0].TargetLoc}设置指定时间,找到库存{productN.OrderBy(t => t.POProdProduct.MdTime).Select(t => t.POProdProduct.MdTime).ToList().ToJson()}", true);
            //}
            ////endregion 到此新增结束
            //根据订单创建任务
            //if (master.POWmsOutOrderSummaries[0].MaterialId == 450121666001895473)
            //{
            //    //WriteLog($"硫化主订单1{master.MasterId}{productN.Select(t => t.POProdProduct.ProductCode).ToJson()},订单数{master.Count}", true);
            //}
            //WriteLog($"StartMaterial,{master.MasterId},{productN.Count}-1119446", true);
            CreateTaskByOrderV2(master, asrsOutInfoBeans, crnForks, platformLocs, wcsAsrsLocHalts, asrsNetOutputs, productN, wcsEquipLocHolds);

            //WriteLog($"StartMaster,{master.MasterId}-999", true);
        }
        //////WriteLog($"CreateTask-1999", true);
    }

    public int ExecuteTask(int taskNo, long locId)
    {
        var task = _Task.GetTaskByTaskNo(taskNo);
        if (task?.Id is not long taskId)
        {
            return 0;
        }
        //_WcsOutputLog.CreateOrUpdateWcsOutputLog(task?.Id ?? 0, taskNo, (int)EnumOutputLogPlan.CrnStart);

        var num = _Task.UpdateTaskAndCmdStatus(locId, taskId, (int)EnumTaskStatus.Executed);

        //OLDTODO 【已解决】添加 执行时位置改变
        // _RcsLocation.UpdateLocationAndWcsLocWithSkuId(task.SkuId, task.StartLoc, task.CurrentLoc);

        //同步MES
        //SyncMesOnExecute(task.SkuId.GetValueOrDefault(), task.SummaryId.GetValueOrDefault(), task.TargetLoc.GetValueOrDefault(), locId);
        // _WcsOutputLog.CreateOrUpdateWcsOutputLog(task?.Id ?? 0, taskNo, (int)EnumOutputLogPlan.CrnEnd);
        return num;
    }

    public int RollExecuteTask(int taskNo, long locId)
    {
        var task = _Task.GetTaskByTaskNo(taskNo);
        if (task?.Id is not long taskId)
        {
            return 0;
        }

        var num = _Task.UpdateTaskAndCmdStatus(locId, taskId, (int)EnumTaskStatus.Executable);

        return num;
    }

    /// <summary>
    /// 同步MES
    /// </summary>
    /// <param name="skuId"></param>
    /// <param name="summaryId"></param>
    /// <param name="targetLoc"></param>
    /// <param name="currentLoc"></param>
    private void SyncMesOnExecute(long skuId, long summaryId, long targetLoc, long currentLoc)
    {
        //出库信息（WMS->MES）开始执行堆垛机出库任务，由WMS将信息推送至MES
        //WriteLog($"开始执行出库信息中间表1", true);
        var tireBarcode = _ProdProduct.GetCodeBySkuId(skuId);
        var curingRL = _RcsEquipCuring.GetCuringRLByCuringLocId(targetLoc);
        var equipNo = curingRL?.CuringCode;
        var model = curingRL?.Mode;
        var equipModel = _RcsEquipCuring.GetCuringRLByMesModelRL(model);
        List<PushWarehousingOutParam> pushWarehousingOutParams = new(){
            new PushWarehousingOutParam
            {
                OrderDetailId = summaryId.ToString(),
                TireBarcode = tireBarcode,
                CurrentLoc = currentLoc.ToString(),
                TargetLoc = targetLoc.ToString(),
                EquipNo = equipNo,
                EquipModel = equipModel
            }
        };
        _Wms2MesService.PushWarehousingOut(pushWarehousingOutParams);


        //WriteLog($"开始执行出库信息中间表2", true);
        // 2.胎胚库存（中间表）

        //_Rpc.SetTireStock(new()
        //{
        //    TirBarCode = tireBarcode,
        //    TireWarehouse = (int)EnumInventoryType.ExWarehousing,
        //});
    }

    //public long GetWarehouseByLocationID(long targetLoc) 
    //{
    //    var warehouseId = _RcsLocation.GetWarehouseByLocationID(targetLoc);
    //    return warehouseId;
    //}

    public int BindOutTask(int taskNo, long locId)
    {
        var taskCmd = _TaskCmd.GetExecutedTaskCmdByTaskNo(taskNo);
        if (taskCmd?.TaskId is not long taskId || taskCmd?.TaskType != (int)EnumTaskType.Exwarehouse)
        {
            return 1;
        }

        var task = _Task.GetTaskByTaskId(taskId);
        var skuId = task.SkuId;

        var result = _WcsLocSku.SetWcsLocSku(locId, skuId, true);

        return result;
    }

    public int FinishTask(int taskNo, long locId)
    {
        // _monitor.CreateFlowLog(2, 1, $"{taskNo}", $"taskNo:{taskNo},locId:{locId}", "关闭出库任务，更新绑定位置");

        //WriteLog($"任务{taskNo}开始执行出库完成", true);
        var taskCmd = _TaskCmd.GetExecutedTaskCmdByTaskNo(taskNo);
        if (taskCmd?.TaskId is not long taskId || taskCmd?.TaskType != (int)EnumTaskType.Exwarehouse)
        {
            return 1;
        }
        //_WcsOutputLog.CreateOrUpdateWcsOutputLog(taskId, taskNo, (int)EnumOutputLogPlan.CrnStart);
        // 获取任务
        var task = _Task.GetTaskByTaskId(taskId);
        var master = _WmsOutOrderMaster.GetOutOrderMasterById(task.MasterId ?? 0);
        var skuId = task.SkuId;
        var targetLoc = taskCmd.TargetLoc.GetValueOrDefault();
        var startLoc = taskCmd.StartLoc.GetValueOrDefault();
        var masterId = task.MasterId ?? 0;


        if (master is null)
        {
            //判断是否从入库取货位来的胎
            var input = _WcsAsrsCrnInput.GetWcsAsrsCrnInputByLoc(startLoc);

            if (input is not null)
            {
                _Task.BakAndDeleteTaskAndCmd(taskId);
                // 同步MES
                //SyncMesOnFinish(task);
                //WriteLog($"任务{taskNo}结束执行出库完成", true);

                return 1;
            }

            // _monitor.CreateFlowLog(2, 2, "", $"taskNo:{taskNo},locId:{locId},master:", "master不是null,开始执行调整库位绑定，将库位绑定清楚，改为出库放胎位绑定");
            // 修改状态
            _Task.UpdateTaskAndCmdStatus(locId, taskId, (int)EnumTaskStatus.Finish);
            // 备份删除
            _TaskCmd.BakAndDeleteCmd(taskId);
            // 修改货位标识
            _RcsLocation.UpdateLocationAndWcsLocWithSkuId(skuId, startLoc, targetLoc, true);
            // 位置绑定流水号
            _PositionService.UpdateRcsLocationIsTaskNo(locId, task.TaskNo.GetValueOrDefault());
            // 获取异常口
            var abnormalLocId = _WcsNetAbnormal.GetAbnormalLocIdByStartLoc(locId);
            // 修改任务异常口
            _Task.UpdateTaskTargetLocRemark(taskId, abnormalLocId, $"订单{masterId}已删除");

            //_monitor.CreateFlowLog(2, 2, "", $"taskNo:{taskNo},locId:{locId},master:{master.ToJson()}", "出库任务实行完成");
            //WriteLog($"任务{taskNo}结束执行出库完成", true);
            return 1;
        }
        if (master.OrderType != (int)EnumCodeOutOrderType.WarehouseLocation)
        {
            _TaskCmd.UpdateTaskCmdStatus(locId, taskId, (int)EnumTaskStatus.Finish);
            //_monitor.CreateFlowLog(2, 2, $"{taskNo}", $"taskNo:{taskNo},locId:{locId},master:", "开始备份删除指令");
            // 备份删除
            _TaskCmd.BakAndDeleteCmd(taskId);
            // 正常请料出库

            //_monitor.CreateFlowLog(2, 2, $"{taskNo}", $"taskNo:{taskNo},locId:{locId},master:", "开始修改货位标识");
            // 修改货位标识
            _RcsLocation.UpdateLocationAndWcsLocWithSkuId(skuId, startLoc, targetLoc, true);
            //_monitor.CreateFlowLog(2, 2, $"{taskNo}", $"taskNo:{taskNo},locId:{locId},master:", "开始位置绑定流水号");
            // 位置绑定流水号
            _PositionService.UpdateRcsLocationIsTaskNo(locId, task.TaskNo.GetValueOrDefault());
            //_monitor.CreateFlowLog(2, 2, $"{taskNo}", $"taskNo:{taskNo},locId:{locId},master:", "开始修改指令状态");
           
            var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(task.SummaryId ?? 0);
            // 同步MES
            try
            {
                //WriteLog($"任务{taskNo}开始同步堆垛机出库mes", true);
                SyncMes(skuId ?? 0, summary, task.TargetLoc ?? 0);
            }
            catch (Exception ex)
            {
                //WriteLog($"任务{taskNo}同步堆垛机出库mes异常,{ex.ToString()}", true);
            }

            //WriteLog($"任务{taskNo}结束执行出库完成", true);
            return 1;
        }
        else
        {
            //_monitor.CreateFlowLog(2, 2, $"{taskNo}", $"taskNo:{taskNo},locId:{locId},master:", "master.OrderType是3,开始执行调整库位绑定，将库位绑定清楚，改为出库放胎位绑定");
            // 库位出库（wcsAsrsCrnAbnormalOutput is null 线体出库；wcsAsrsCrnAbnormalOutput is not null 堆垛机出库）
            var wcsAsrsCrnAbnormalOutput = _WcsAsrsCrnAbnormalOutPut.GetAsrsCrnAbnormalOutPutByLocId(targetLoc);
            if (wcsAsrsCrnAbnormalOutput is null)
            {

                // 修改状态
                _TaskCmd.UpdateTaskCmdStatus(locId, taskId, (int)EnumTaskStatus.Finish);
                // 备份删除
                _TaskCmd.BakAndDeleteCmd(taskId);
                //出库到异常线体
                _RcsLocation.UpdateLocationAndWcsLocWithSkuId(skuId, startLoc, targetLoc, true);
                var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(task.SummaryId ?? 0);
                //人工出库也同步MES
                try
                {
                    //WriteLog($"任务{taskNo}开始同步出库mes", true);
                    SyncMes(skuId ?? 0, summary, targetLoc);
                }
                catch (Exception ex)
                {
                    //WriteLog($"任务{taskNo}同步出库mes异常,{ex.ToString()}", true);
                }
                //WriteLog($"任务{taskNo}结束执行出库完成", true);
                return 2;
            }
            else
            {
                var barCode = _ProdProduct.GetCodeBySkuId(task.SkuId ?? 0);
                // 指令完成
                _Task.UpdateTaskAndCmdStatus(locId, taskId, (int)EnumTaskStatus.Finish);
                //WriteLog($"开始执行异常出库任务号{task.TaskNo}", true);
                //// 同步MES
                //SyncMesOnFinish(task);
                SyncAbnormalMes(barCode, task.StartLoc ?? 0, task.TargetLoc ?? 0);

                //WriteLog($"执行完成异常出库任务号{task.TaskNo}", true);
                // 立库异常删除订单和任务
                _RcsLocation.UpdateLocationNoGood(startLoc);
                // 任务指令备份删除
                _Task.BakAndDeleteTaskAndCmd(taskId);
                // 清空开始位置 和 skuID
                _WcsLocSku.DeleteWcsLocSkuBySkuLoc(skuId, targetLoc);
                // 完成数量
                _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(task.SummaryId.GetValueOrDefault());
                var summaryCount = _WmsOutOrderSummary.GetOutOrderSummaryByMasterId(master.Id.GetValueOrDefault()).Count();
                if (summaryCount == 0)
                {
                    _WmsOutOrderMaster.BakOutOderMaster(master);
                    _WmsOutOrderMaster.DeleteOutOderMaster(master.Id);
                }
                //WriteLog($"任务{taskNo}结束执行出库完成", true);
                return 3;
            }
        }

    }



    /// <summary>
    /// 同步MES
    /// </summary>
    /// <param name="barCode"></param>
    /// <param name="startLoc"></param>
    /// <param name="taskId"></param>
    private void SyncAbnormalMes(string barCode, long startLoc, long targetLoc)
    {
        // 16.异常输送（WMS->MES）
        _Wms2MesService.PushAbnormal(barCode, startLoc, targetLoc);
    }

    /// <summary>
    /// 拆分订单
    /// </summary>
    private void SplitOrder(OrderSummaryGroupyMaster master)
    {

        var masterNewId = _WmsOutOrderMaster.AddOutOrderMaster(master.OrderType);
        _WmsOutOrderSummary.UpdateOrderSummaryMasterId(master.POWmsOutOrderSummaries[1].Id.GetValueOrDefault(), master.MasterId, masterNewId);
    }

    /// <summary>
    /// 出库订单按照顺序，硫化排排序
    /// </summary>
    /// <param name="orderSummaryGroupies"></param>
    /// <param name="newSummary"></param>
    /// <param name="ditchId"></param>
    private void OderSummary(List<OrderSummaryGroupyMaster> orderSummaryGroupies, ref List<OrderSummaryGroupyMaster> newSummary, long ditchId = 0)
    {
        for (int i = 0; i < orderSummaryGroupies.Count; i++)
        {
            if (orderSummaryGroupies[i].DitchId != ditchId)
            {
                newSummary.Add(orderSummaryGroupies[i]);
                ditchId = orderSummaryGroupies[i].DitchId;
                orderSummaryGroupies.Remove(orderSummaryGroupies[i]);
                i--;
            }
        }
        if (orderSummaryGroupies.Count > 0)
        {
            OderSummary(orderSummaryGroupies, ref newSummary);
        }
    }

    //根据单据创建出库任务   单据-出库路线-货叉信息-出库站台-停机货位
    private void CreateTaskByOrderV2(OrderSummaryGroupyMaster master, List<WcsAsrsNetOutputGroup> asrsOutInfoBeans, List<CrnForkInfo> crnForks,
        List<CrnOutLoc> platformLocs, List<POWcsAsrsLocHalt> wcsAsrsLocHalts, List<NetOutEntity> asrsNetOutputs, List<ProductLocBean> productN,
        List<POWcsEquipLocHold> wcsEquipLocHolds)
    {
        //WriteLog($"CreateTaskByOrderV2-111", true);
        // 获取过期时间 当前时间 - 配置时间
        var summaryids = master.POWmsOutOrderSummaries.Select(t => t.Id.GetValueOrDefault()).ToList();
        var newDate = DateTime.Now;
        //非请料：执行；请料：任务数满停止，任务数不满继续 
        if (_RcsEquipCuringDitch.IsCallMaterialExceed(master))
        {
            _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"硫化排缓存数满");
            return;
        }
        //WriteLog($"CreateTaskByOrderV2-222", true);
        // 判断订单数和实际要执行的数量是否一致
        var masterId = master.MasterId;
        var summarys = _WmsOutOrderSummary.GetOutOrderSummaryByMasterId(masterId);
        var requestCount = summarys.Where(t => t.PlanCount > t.RealCount).Count();
        if (summaryids.Count != requestCount)
        {
            var prodMaterial = _ProdMaterial.GetMaterialById(masterId);
            var spec = prodMaterial?.Spec;

            _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"出库订单{spec}实际生成任务数{summaryids.Count}与可生成任务数{requestCount}不一致{newDate}");
            return;
        }
        //WriteLog($"CreateTaskByOrderV2-333", true);
        // 库存信息 此处判断了物料是否超期
        var (summaryMaterials, materialIds, locationGroups) = GetMaterialLocationV2(master, crnForks, productN, wcsEquipLocHolds);

        //WriteLog($"CreateTaskByOrderV2-444", true);
        var locations = GetOtherTimeLocsV3(summaryMaterials, materialIds, locationGroups);
        //WriteLog($"CreateTaskByOrderV2-555", true);
        if (!locations.Any())
        {
            _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"未过期,满足条件库位数量{locations.Count}不足{newDate}");
            return;
        }
        //WriteLog($"CreateTaskByOrderV2-666", true);
        // 可用堆垛机
        var crnIds = crnForks.Where(t => t.IsEnable == true).Select(t => t.CrnId).ToList();

        var asrsNetOutputsNoTask = GetAsrsNetOutPuts(asrsNetOutputs, locations, platformLocs, crnIds);
        //WriteLog($"CreateTaskByOrderV2-777", true);
        if (asrsNetOutputsNoTask.Count == 0)
        {
            // 没有可选路线（原因：生成一个任务会删除一条出库路线，最终可能找不到出库路线），重新查找所有可用出库路线
            var asrsOutInfoBeans_01 = _WcsAsrsNetOutPut.GetAsrsNetOutputByForkInfo(crnForks);
            var asrsNetOutputs_01 = IsNetOutBySummaryTarget(master, asrsOutInfoBeans_01);
            if (asrsNetOutputs_01.Count == asrsNetOutputs.Count)
            {
                _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"未过期{asrsNetOutputs_01.Count},站台位数量{platformLocs.Count}[堆垛机出库任务满1],没有可选择出库路线{newDate}.");
                //WriteLog($"CreateTaskByOrderV2-7771", true);
                //WriteLog($"未过期{summaryids.ToJson()},{crnIds.ToJson()},{asrsOutInfoBeans_01.Count},{asrsNetOutputs_01.Count},{asrsNetOutputs.Count},{asrsNetOutputs_01.Count},{locations.Count}站台位1:{platformLocs.ToJson()}", true);

                return;
            }
            //WriteLog($"CreateTaskByOrderV2-888", true);
            asrsNetOutputsNoTask = GetAsrsNetOutPuts(asrsNetOutputs_01, locations, platformLocs, crnIds);
            if (asrsNetOutputsNoTask.Count == 0)
            {
                _WmsOutOrderSummary.UpdateOrderSummaryRemark(summaryids, $"未过期,站台位数量{platformLocs.Count}[可能堆垛机出库任务满2],没有可选择出库路线{newDate}.");

                //WriteLog($"未过期{summaryids.ToJson()},{crnIds.ToJson()},{asrsOutInfoBeans_01.Count},{asrsNetOutputs_01.Count},{asrsNetOutputsNoTask.Count},{asrsNetOutputs.Count},{locations.Count}站台位2:{platformLocs.ToJson()}", true);

                return;
            }
        }
        //WriteLog($"CreateTaskByOrderV2-999", true);
        //根据路线分值创建任务  堆垛机货叉路线信息，出库路线，出库站台，货车停机货位，出库订单，库位
        _WarehousOut.CreateTaskRoutineV2(asrsOutInfoBeans, asrsNetOutputsNoTask, platformLocs, wcsAsrsLocHalts, master, locations);
        //WriteLog($"CreateTaskByOrderV2-1010", true);

    }

    private List<NetOutEntity> GetAsrsNetOutPuts(List<NetOutEntity> asrsNetOutputs, List<CanStock> locations, List<CrnOutLoc> platformLocs, List<long?> crnIds)
    {
        var asrsNetOutputsNoTask = asrsNetOutputs.Join(locations, f => f.CrnId, s => s.CrnId,
        (f, s) => new NetOutEntity
        {
            AreaId = f.AreaId,
            CrnId = f.CrnId,
            RelateScore = f.RelateScore,
            //当前堆垛机可用货叉-可用货叉数量-出库路线
            NetOutPut = f.NetOutPut,
            MinTime = s.MinTime,
            LocationGroupInfos = s.LocationGroupInfos.ToList(),
            IsTimeOut = s.IsTimeOut,
        }).Join(platformLocs, f => new { f.AreaId, f.CrnId }, s => new { s.AreaId, s.CrnId }, (f, s) => new NetOutEntity
        {
            AreaId = f.AreaId,
            CrnId = f.CrnId,
            RelateScore = f.RelateScore,
            NetOutPut = f.NetOutPut,
            MinTime = f.MinTime,
            LocationGroupInfos = f.LocationGroupInfos,
            NowCount = s.NowCount,
            IsTimeOut = f.IsTimeOut,
        }).Where(t => crnIds.Contains(t.CrnId))
        .OrderByDescending(t => t.IsTimeOut)
        .ThenBy(t => t.MinTime)
        .ThenBy(t => t.RelateScore)
        .ThenBy(t => t.NowCount).ToList();  // 升序

        return asrsNetOutputsNoTask;

    }

    ///// <summary>
    ///// 请料-硫化排任务数量是否超限
    ///// </summary>
    ///// <returns>true 退出；false 执行</returns>
    //private bool IsCallMaterialExceed(OrderSummaryGroupyMaster master)
    //{
    //    // 硫化机请料、条码请料、规格请料 硫化排是否满胎
    //    var order = _WmsOutOrderMaster.GetOutOrderMasterById(master.MasterId);
    //    if (order?.OrderType == (int)EnumCodeOutOrderType.RequesMaterial
    //        || order?.OrderType == (int)EnumCodeOutOrderType.WarehouseProductCode
    //        || order?.OrderType == (int)EnumCodeOutOrderType.WarehouseMaterial)
    //    {
    //        var targetLoc = master.POWmsOutOrderSummaries.FirstOrDefault().TargetLoc;
    //        var isCreateTask = _WmsOutOrderSummary.IsCuringDitchTaskCount(targetLoc.GetValueOrDefault());
    //        if (!isCreateTask)
    //        {
    //            return true;
    //        }
    //    }

    //    return false;
    //}

    /// <summary>
    /// 是否有到达硫化机的路线
    /// </summary>
    /// <returns></returns>
    private List<NetOutEntity> IsNetOutBySummaryTarget(OrderSummaryGroupyMaster master, List<WcsAsrsNetOutputGroup> asrsOutInfoBeans)
    {
        // 当前请料订单目标位置
        var targetLocs = master.POWmsOutOrderSummaries.Select(x => x.TargetLoc).ToList();

        // 到达目标位置出库路线【区域——堆垛机——具体路线信息】
        var asrsNetOutputs = asrsOutInfoBeans
            .Where(t => targetLocs.Contains(t.WcsAsrsNetOutputs.TargetLoc))
            .GroupBy(t => new { t.WcsAsrsNetOutputs.AreaId, t.WcsAsrsNetOutputs.CrnId, t.WcsAsrsNetOutputs.RelateScore })
            .Select(t => new NetOutEntity
            {
                AreaId = t.Key.AreaId,
                CrnId = t.Key.CrnId,
                RelateScore = t.Key.RelateScore,
                // 当前堆垛机可用货叉-可用货叉数量-出库路线
                NetOutPut = t.FirstOrDefault(),
            })
            .OrderBy(t => t.RelateScore)
            .ToList();
        return asrsNetOutputs;
    }


    private (List<MaterialCount>, List<long>, List<LocationGroupInfo>) GetMaterialLocationV2(OrderSummaryGroupyMaster master,
        List<CrnForkInfo> crnForks,
        List<ProductLocBean> productN,
        List<POWcsEquipLocHold> wcsEquipLocHolds)
    {
        //GetMaterialLocationV2
        //WriteLog($"GetMaterialLocationV2-111", true);
        //OLDTODO 【已解决】物料判断，逻辑在改改 （等到出库明细物料和出库数量  物料 需出库数量）
        var summaryMaterials = master.POWmsOutOrderSummaries
            .GroupBy(t => t.MaterialId)
            .Select(t =>
            new MaterialCount { MaterialId = t.Key.Value, Count = t.Sum(x => x.PlanCount - x.RealCount).GetValueOrDefault() })
            .Where(t => t.Count > 0)
            .ToList();
        //WriteLog($"GetMaterialLocationV2-222", true);
        //(出库明细所需物料  物料)
        var materialIds = summaryMaterials
            .Select(t => t.MaterialId)
            .Distinct()
            .ToList();
        //WriteLog($"GetMaterialLocationV2-333", true);
        // 获取堆垛机-物料-货位集合(去掉了异常货叉的停机货位)
        var locationGroups = _RcsLocation.GetGoodsLocationByAreaIdGroupV2(crnForks, productN, wcsEquipLocHolds);
        //WriteLog($"GetMaterialLocationV2-444", true);
        return (summaryMaterials, materialIds, locationGroups);
    }

    private List<CanStock> GetOtherTimeLocsV3(List<MaterialCount> summaryMaterials, List<long> materialIds, List<LocationGroupInfo> locationGroups)
    {
        var locations = locationGroups
        .Where(t => materialIds.Contains(t.MaterialId.GetValueOrDefault()))
        .GroupBy(t => t.CrnId)
        .Select(t => new CanStock
        {
            CrnId = t.Key.Value,
            MinTime = t.Min(t => t.MinTime).GetValueOrDefault(),
            IsTimeOut = t.Count(t => t.IsTimeOut == 1) > 0 ? 1 : 0,
            LocationGroupInfos = t.Where(x =>
            x.LocationInfos.Count >=
            summaryMaterials.Where(s => s.MaterialId == x.MaterialId).FirstOrDefault().Count)
            .ToList(),
        }).Where(t => t.LocationGroupInfos.Count == materialIds.Count).OrderBy(t => t.MinTime).ToList();
        return locations;
    }

    /// <summary>
    /// 删除无效出库订单(先备份再删除)
    /// </summary>
    public void DeleteInvalidOutOrder()
    {
        DateTime dateTime = DateTime.Now.AddMinutes(-2);
        BakAndDeleteOutOrderSummary(dateTime);
        BakAndDeleteOutOrderMaster(dateTime);
        BakAndDeleteOutOrderWithInvalidTask(dateTime);
    }
    /// <summary>
    /// 备份、删除不存在主表数据的出库订单从表
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public int BakAndDeleteOutOrderSummary(DateTime dateTime)
    {
        var db = Db.Default;
        var outOrderSummarys = (from s in db.WmsOutOrderSummarys
                                where s.CreateTime < dateTime
                                && !(from m in db.WmsOutOrderMasters select m.Id).Contains(s.MasterId)
                                select s).ToList();
        if (outOrderSummarys.Count == 0)
        {
            return 0;
        }
        var result = 0;
        result += BakOutOderSummary(outOrderSummarys);
        var ids = outOrderSummarys.Select(s => s.Id).ToList();
        result += DeleteOutOderSummary(ids);

        return result;
    }
    /// <summary>
    /// 备份、删除不存在从表数据的出库订单主表
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public int BakAndDeleteOutOrderMaster(DateTime dateTime)
    {
        var db = Db.Default;
        var outOrderMasters = (from m in db.WmsOutOrderMasters
                               where m.CreateTime < dateTime
                               && !(from s in db.WmsOutOrderSummarys select s.MasterId).Contains(m.Id)
                               select m).ToList();
        if (outOrderMasters.Count == 0)
        {
            return 0;
        }
        var result = 0;
        result += BakOutOderMaster(outOrderMasters);
        var ids = outOrderMasters.Select(s => s.Id).ToList();
        result += DeleteOutOderMaster(ids);

        return result;
    }
    /// <summary>
    /// 备份、删除已生成任务但不存在任务数据的出库订单主从表
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public int BakAndDeleteOutOrderWithInvalidTask(DateTime dateTime)
    {
        var db = Db.Default;
        var outOrders = (from m in db.WmsOutOrderMasters
                         join s in db.WmsOutOrderSummarys
                         on m.Id equals s.MasterId
                         where m.CreateTime < dateTime && s.CreateTime < dateTime && s.RealCount == 1
                         && !(from t in db.WcsTasks select t.SummaryId).Contains(s.Id)
                         select new { OutOrderMaster = m, OutOrderSummary = s }).ToList();
        if (outOrders.Count == 0)
        {
            return 0;
        }
        var result = 0;
        var outOrderSummary = outOrders.Select(s => s.OutOrderSummary).ToList();
        var outOrderMasters = outOrders.Select(s => s.OutOrderMaster).Distinct().ToList();
        result += BakOutOderSummary(outOrderSummary);
        result += BakOutOderMaster(outOrderMasters);

        var summaryIds = outOrderSummary.Select(s => s.Id).ToList();
        result += DeleteOutOderSummary(summaryIds);
        var masterIds = outOrderMasters.Select(s => s.Id).ToList();
        result += DeleteOutOderMaster(masterIds);

        return result;
    }

    /// <summary>
    /// 备份出库订单主表
    /// </summary>
    /// <param name="wmsOutOrderMasters"></param>
    /// <returns></returns>
    public int BakOutOderMaster(List<POWmsOutOrderMaster> wmsOutOrderMasters)
    {
        var db = Db.Default;

        foreach (var wmsOutOrderMaster in wmsOutOrderMasters)
        {
            var entity = wmsOutOrderMaster.Map<POBakWmsOutOrderMaster>();
            entity.FinishMode = (int)EnumFinishMode.SystemDelete;
            db.BakWmsOutOrderMasters.Add(entity);
        }

        var result = 0;
        try
        {
            result = db.SaveChanges();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }
    /// <summary>
    /// 删除出库订单主表
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public int DeleteOutOderMaster(List<long?> ids)
    {
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.WmsOutOrderMasters.Where(t => ids.Contains(t.Id)).Delete();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }
    /// <summary>
    /// 备份出库订单从表
    /// </summary>
    /// <param name="wmsOutOrderSummarys"></param>
    /// <returns></returns>
    public int BakOutOderSummary(List<POWmsOutOrderSummary> wmsOutOrderSummarys)
    {
        var db = Db.Default;

        foreach (var wmsOutOrderSummary in wmsOutOrderSummarys)
        {
            var entity = wmsOutOrderSummary.Map<POBakWmsOutOrderSummary>();
            entity.FinishMode = (int)EnumFinishMode.SystemDelete;
            db.BakWmsOutOrderSummarys.Add(entity);
        }

        var result = 0;
        try
        {
            result = db.SaveChanges();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }

        return result;
    }
    /// <summary>
    /// 删除出库订单从表
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public int DeleteOutOderSummary(List<long?> ids)
    {
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.WmsOutOrderSummarys.Where(t => ids.Contains(t.Id)).Delete();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }

    /// <summary>
    /// 删除无效出库任务
    /// </summary>
    public void DeleteInvalidTask()
    {
        var db = Db.Default;
        DateTime dateTime = DateTime.Now.AddHours(-8);
        var tasks = (from t in db.WcsTasks
                     where t.TaskType == (int)EnumTaskType.Transportation
                     && t.CreateTime < dateTime
                     select t).ToList();
        if (tasks.Count > 0)
        {
            var summaryId = tasks.Select(s => s.SummaryId).ToList();
            var outOrders = (from m in db.WmsOutOrderMasters
                             join s in db.WmsOutOrderSummarys
                             on m.Id equals s.MasterId
                             where summaryId.Contains(s.Id)
                             select new { OutOrderMaster = m, OutOrderSummary = s }).ToList();

            //var outOrders = (from m in db.WmsOutOrderMasters
            //                 join s in db.WmsOutOrderSummarys
            //                 on m.Id equals s.MasterId
            //                 where (from t in db.WcsTasks where t.CreateTime < dateTime select t.SummaryId).Contains(s.Id)
            //                 select new { OutOrderMaster = m, OutOrderSummary = s }).ToList();


            if (outOrders.Count > 0)
            {
                var outOrderSummary = outOrders.Select(s => s.OutOrderSummary).ToList();
                var outOrderMasters = outOrders.Select(s => s.OutOrderMaster).Distinct().ToList();
                BakOutOderSummary(outOrderSummary);
                BakOutOderMaster(outOrderMasters);

                var summaryIds = outOrderSummary.Select(s => s.Id).ToList();
                DeleteOutOderSummary(summaryIds);
                var masterIds = outOrderMasters.Select(s => s.Id).ToList();
                DeleteOutOderMaster(masterIds);
            }

            var ids = tasks.Select(s => s.Id).ToList();
            var taskCmds = (from c in db.WcsTaskCmds
                            where ids.Contains(c.TaskId)
                            select c).ToList();
            if (taskCmds.Count > 0)
            {
                BakTaskCmd(taskCmds);
                var cmdIds = taskCmds.Select(s => s.Id).ToList();
                DeleteTaskCmd(cmdIds);
            }
            BakTask(tasks);
            var taskIds = tasks.Select(s => s.Id).ToList();
            DeleteTask(taskIds);
        }
    }
    /// <summary>
    /// 备份任务表
    /// </summary>
    /// <param name="tasks"></param>
    /// <returns></returns>
    public int BakTask(List<POWcsTask> tasks)
    {
        var db = Db.Default;

        foreach (var task in tasks)
        {
            var entity = task.Map<POBakWcsTask>();
            entity.FinishMode = (int)EnumFinishMode.SystemDelete;
            db.BakWcsTasks.Add(entity);
        }

        var result = 0;
        try
        {
            result = db.SaveChanges();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }
    /// <summary>
    /// 删除任务表
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public int DeleteTask(List<long?> ids)
    {
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.WcsTasks.Where(t => ids.Contains(t.Id)).Delete();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }
    /// <summary>
    /// 备份任务指令表
    /// </summary>
    /// <param name="taskCmds"></param>
    /// <returns></returns>
    public int BakTaskCmd(List<POWcsTaskCmd> taskCmds)
    {
        var db = Db.Default;

        foreach (var taskCmd in taskCmds)
        {
            var entity = taskCmd.Map<POBakWcsTaskCmd>();
            entity.FinishMode = (int)EnumFinishMode.SystemDelete;
            db.BakWcsTaskCmds.Add(entity);
        }

        var result = 0;
        try
        {
            result = db.SaveChanges();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }
    /// <summary>
    /// 删除任务指令表
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public int DeleteTaskCmd(List<long?> ids)
    {
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.WcsTaskCmds.Where(t => ids.Contains(t.Id)).Delete();
        }
        catch (Exception ex)
        {
            //WriteLog(ex.ToString(), true);
        }
        return result;
    }

    /// <summary>
    /// 同步MES
    /// </summary>
    /// <param name="skuId"></param>
    /// <param name="summaryId"></param>
    /// <param name="targetLoc"></param>
    private void SyncMes(long skuId, POWmsOutOrderSummary summary, long targetLoc)
    {
        //crn完成开始推送信息skuId-603892304247259637,summary605316946560287221,targetloc20060802
        //WriteLog($"crn完成开始推送信息skuId-{skuId},summary{summary?.Id},targetloc{targetLoc}", true);
        var tireBarcode = _ProdProduct.GetCodeBySkuId(skuId);
        //WriteLog($"ems完成开始推送信息tireBarcode-{tireBarcode}", true);
        var curingRL = _RcsEquipCuring.GetCuringRLByCuringLocId(targetLoc);
        var equipNo = curingRL?.CuringCode;
        var model = curingRL?.Mode;
        //var equipModel = _RcsEquipCuring.GetCuringRLByMesModelRL(model);
        //var summmary = _WmsOutOrderSummary.GetOutOrderSummaryById(summary?.Id ?? 0);
        var material = _ProdMaterial.GetMaterialById(summary?.MaterialId ?? 0);
        //_WcsEquipLocHold.GetEquipLocHoldByLoc(summmary.StartLoc ?? 0)
        //if (summary.CrnId == 10030901 || summary.CrnId == 10031001 || summary.CrnId == 10031101 || summary.CrnId == 10031201
        //    || summary.CrnId == 10031301 || summary.CrnId == 10031401 || summary.CrnId == 10031501 || summary.CrnId == 10031601)
        //{
        //    if (model == "L")
        //    {
        //        model = "R";
        //    }
        //    else
        //    {
        //        model = "L";
        //    }

        //}


        var mesService = K8.RSF.Client.Create<IMesService>();
        EndParam param = new EndParam()
        {
            TcmNo = equipNo,
            TcmDir = model,
            TcmSpec = material?.MaterialCode,
            TcmSpecDesc = material?.MaterialCode,
            TirCode = tireBarcode,
            Angle = 0,
            TbmPs = summary.TbmPs ?? "",
            CompFlag = "S",
            //TbmSpec=mesproduct?.TbmSpec
        };
        mesService.AddOutEnd(param);

    }

    /// <summary>
    /// 创建订单
    /// </summary>
    public void CreateOutSummaries()
    {
        WriteLog("创建出库订单1", true);
        var mesServices = K8.RSF.Client.Create<IMesService>();
        try
        {
            var tcmInfoTask = Task.Run(() => { return mesServices.GetAllInCuringInfos(); });
            //var tcmInfoTask = Task.Run(() => { return GetAllInCuringInfos(); });

            var summaryTaskCountsTask = Task.Run(() => { return _WmsOutOrderSummary.GetTaskSummaryOccupyCount(); });

            var SummaryOccupyTasks = Task.Run(() => { return _WmsOutOrderSummary.GetOccupySummarys(); });

            var locProductsTask = Task.Run(() => { return _ProdProduct.GetLocProductBeans(); });

            var tcmInfos = tcmInfoTask.Result;

            if (tcmInfos is null || !tcmInfos.Any())
            {
                WriteLog("所有机台未请料", true);

                return;
            }


            WriteLog("创建出库订单2", true);
            var materialCodes = tcmInfos.Select(f => f.TBM_SPEC).ToList();

            var MaterialMsgsTask = Task.Run(() => { return _ProdMaterial.GetMaterialByCodes(materialCodes); });

            var summaryTaskCount = summaryTaskCountsTask.Result;

            var locProducts = locProductsTask.Result;

            //if (locProducts is null || !locProducts.Any())
            //{
            //    //WriteLog($"库存不足，不生成订单", true);

            //    return;
            //}

            //var summaryOccupy = SummaryOccupyTasks.Result;

            //if (summaryOccupy is not null && summaryOccupy.Any())
            //{
            //    var summaryStartLocs = summaryOccupy.Select(f => f.StartLoc).ToList();

            //    locProducts = locProducts.Where(f => !summaryStartLocs.Contains(f.LocId)).ToList();

            //    if (locProducts is null || !locProducts.Any())
            //    {
            //        //WriteLog($"库存不足，不生成订单,现有库存都已被订单占用。", true);

            //        return;
            //    }
            //}

            var manager = new SummaryManager();

            //List<TcmInfo> syncMesList = new List<TcmInfo>();
            WriteLog("创建出库订单3", true);
            foreach (var info in tcmInfos)
            {
                var OccupyMsg = summaryTaskCount.Where(f => f.CuringCode == info.TCM_NO && f.CuringDir == info.TCM_DIR).FirstOrDefault();

                if (info.REQ_GT_REQ == "X" || info.REQ_LD_GT == "X" || info.REQ_CV_GT == "X")
                {
                    info.ActualRequireAmount = 0;

                    var remark = $" {info.TCM_NO}-{info.TCM_DIR}硫化机/机械臂/存胎器有停用，硫化机是否停用：{info.REQ_GT_REQ == "X"} ,机械臂是否停用：{info.REQ_LD_GT == "X"}，存胎器是否停用：{info.REQ_CV_GT == "X"} | {DateTime.Now}";

                    manager.UpdateCuringRemark(OccupyMsg?.EquipId ?? 0, remark);

                    continue;
                }

                (info.ActualRequireAmount, info.Priority) = GetInfoCount(info);
                info.ActualRequireAmount = info.ActualRequireAmount - (OccupyMsg?.SummaryCount ?? 0) - (OccupyMsg?.InCuringCount ?? 0);

                //if (info.ActualRequireAmount <= 0)
                if (OccupyMsg?.SummaryCount + OccupyMsg?.InCuringCount > 0)
                {
                    var remark = $" {info.TCM_NO}-{info.TCM_DIR}已生成指定数量的订单，需求数量：{GetInfoCount(info).count},订单数量：{OccupyMsg?.SummaryCount ?? 0},任务数量：{OccupyMsg?.InCuringCount} | {DateTime.Now}";
                    //WriteLog(remark, true);
                    if (info.RCV_FLAG == "N" && GetInfoCount(info).count > 0)
                    {
                        //syncMesList.Add(new TcmInfo { TCM_NO = info.TCM_NO, TCM_DIR = info.TCM_DIR });

                        //mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = info.TCM_NO, TCM_DIR = info.TCM_DIR });
                    }
                    //如果是未生成任务的请料单 判断原物料跟现在物料是否一致
                    if (OccupyMsg?.SummaryCount > 0 && OccupyMsg?.InCuringCount == 0)
                    {
                        //WriteLog($"{info.TCM_NO}已生成指定数量的订单,开始判断物料是否一致", true);
                        //如果不一致 删除对应请料单
                        try
                        {
                            var updatesummary = _WmsOutOrderSummary.UpdateSummaryByTcmNoAndSpec(info.TCM_NO, info.TBM_SPEC);
                            //WriteLog($"{info.TCM_NO}已生成指定数量的订单,结束判断物料是否一致-{updatesummary}", true);
                        }
                        catch (Exception ex)
                        {
                            //WriteLog($"{info.TCM_NO}重置订单异常订单{ex.ToString()}", true);
                        }


                    }
                    manager.UpdateCuringRemark(OccupyMsg?.EquipId ?? 0, remark);

                    continue;
                }
            }

            WriteLog("创建出库订单4", true);
            tcmInfos = tcmInfos.Where(f => f.ActualRequireAmount > 0).OrderBy(f => f.REQ_SULFOPEN_TIME).ToList();


            var materialMsgs = MaterialMsgsTask.Result;


            var curingCodes = tcmInfos.Select(f => f.TCM_NO).Distinct().ToList();

            foreach (var curingCode in curingCodes)
            {
                var curingTcmInfos = tcmInfos.Where(f => f.TCM_NO == curingCode && f.ActualRequireAmount > 0).ToList();

                if (curingTcmInfos is null || !curingTcmInfos.Any())
                {
                    continue;
                }

                var curings = _RcsEquipCuring.GetEquipCuringsByCode(curingCode);

                if (curings is null || !curings.Any())
                {
                    var remark = $" 未找到此硫化机-{curingCode}，或此硫化机-{curingCode}-已禁用 | {DateTime.Now}";

                    //manager.UpdateCuringRemark(curingCode, remark);
                    manager.UpdateCuringRemark2(curings.Select(f => f.Id).ToList(), remark);
                    continue;
                }


                var direction = curings.FirstOrDefault()?.Direction;
                var leftSummaryIndex = 1;
                var rightSummaryIndex = 2;

                if (direction == ConstFields.DirectionN)
                {
                    leftSummaryIndex = 2;
                    rightSummaryIndex = 1;
                }



                var sendTime = curings.OrderByDescending(f => f.SendTime).FirstOrDefault()?.SendTime ?? DateTime.Now.AddMinutes(-1);

                //送胎后等待四秒后再生成
                var enableRequestTime = sendTime.AddSeconds(4);

                if (DateTime.Now < enableRequestTime)
                {
                    var remark = $" 硫化机-{curingCode},刚刚送完，未到允许请料时间，允许请料时间：{enableRequestTime.ToString("yyyy-MM-dd HH:mm:ss.fff")} | {DateTime.Now}";

                    manager.UpdateCuringRemark2(curings.Select(f => f.Id).ToList(), remark);
                }

                cache.TryGetValue(curingCode, out var cacheDateTime);

                //单模请料
                if (curingTcmInfos.Count() == 1)
                {
                    continue;
                    //单模请料直接退出
                    //TODO暂时注释

                    if (!cacheDateTime.HasValue)
                    {
                        cache.TryAdd(curingCode, DateTime.Now);

                        continue;
                    }

                    //单模-等待十秒
                    var endtime = ((DateTime)(cacheDateTime)).AddSeconds(30);


                    if (endtime < DateTime.Now)
                    {
                        var curingTcmInfo = curingTcmInfos.FirstOrDefault();

                        var curingInfo = summaryTaskCount.Where(f => f.CuringCode == curingTcmInfo.TCM_NO && f.CuringDir == curingTcmInfo.TCM_DIR).FirstOrDefault();


                        //var locProduct = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).FirstOrDefault();

                        var stock = 1;// locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).Count();

                        //#region 库存校验
                        //if (locProduct is null)
                        //{
                        //    var NotEnableCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocEnable == 0).Count();
                        //    var tireLocCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.TireLoc == 1).Count();
                        //    var NotOutEnableCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocOutEnable == 0).Count();
                        //    var TaskOccupyCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocTaskOccupy == 1).Count();

                        //    var remark = $"{curingTcmInfo.TCM_NO}-{curingTcmInfo.TCM_DIR} ,需要物料：{curingTcmInfo.TBM_SPEC}，库存不足，需求数量：{GetInfoCount(curingTcmInfo)},不可用数量：{NotEnableCount},锁定数量：{tireLocCount},不可出库数量：{NotOutEnableCount}，任务占用数量：{TaskOccupyCount} | {DateTime.Now}";

                        //    manager.UpdateCuringRemark(curingInfo?.EquipId ?? 0, remark);

                        //    continue;
                        //}
                        //#endregion

                        var materialId = materialMsgs.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC).FirstOrDefault()?.Id ?? 0;

                        var occupyMsg = summaryTaskCount.Where(f => f.CuringCode == curingTcmInfo.TCM_NO && f.CuringDir == curingTcmInfo.TCM_DIR).FirstOrDefault();

                        if (materialId <= 0)
                        {
                            var remark = $" 硫化机-{curingCode}-{curingTcmInfo.TCM_DIR},生产物料：{curingTcmInfo.TBM_SPEC}不存在，该物料从未入库，暂不生成订单 | {DateTime.Now}";

                            manager.UpdateCuringRemark(occupyMsg?.EquipId ?? 0, remark);

                            continue;
                        }

                        var master = manager.AddOutMasters((int)EnumCodeOutOrderType.RequesMaterial);

                        manager.AddOutOrderSummary(new POWmsOutOrderSummary
                        {
                            Id = XID.Nextval,
                            MasterId = master.Id,
                            SummaryIndex = curingTcmInfo.Priority,//设置为当时硫化机要胎的总数，越多，优先级越高
                            TargetLoc = curingInfo.LocId,
                            MaterialId = materialId,
                            Stock = stock,
                            RotateAngle = curingTcmInfo.TCM_ANGLE,
                            TbmPs = curingTcmInfo.TBM_PS,
                            CuringSpec = curingTcmInfo.TBM_SPEC,
                            CuringSpecDesc = curingTcmInfo.TBM_SPEC_DESC,
                            SkuBatch = $"Curing:{curingTcmInfo.REQ_GT_REQ}-Arm:{curingTcmInfo.REQ_LD_GT}-CV:{curingTcmInfo.REQ_CV_GT}-[orderCount:{(occupyMsg?.SummaryCount ?? 0) + (occupyMsg?.InCuringCount)}]",
                        });

                        //syncMesList.Add(new TcmInfo { TCM_NO = curingTcmInfo.TCM_NO, TCM_DIR = curingTcmInfo.TCM_DIR });

                        mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = curingTcmInfo.TCM_NO, TCM_DIR = curingTcmInfo.TCM_DIR });
                        // locProducts.Remove(locProduct);

                        try
                        {
                            cache.TryRemove(curingCode, out _);
                        }
                        catch (Exception ex) { }
                    }

                    continue;
                }

                //双模请料
                if (curingTcmInfos.Count() == 2)
                {
                    var leftInfo = curingTcmInfos.Where(f => f.TCM_NO == curingCode && f.TCM_DIR == "L").FirstOrDefault();
                    var rightInfo = curingTcmInfos.Where(f => f.TCM_NO == curingCode && f.TCM_DIR == "R").FirstOrDefault();

                    if (leftInfo is null || rightInfo is null)
                    {
                        continue;
                    }

                    var leftCuringInfo = summaryTaskCount.Where(f => f.CuringCode == leftInfo.TCM_NO && f.CuringDir == leftInfo.TCM_DIR).FirstOrDefault();
                    var rightCuringInfo = summaryTaskCount.Where(f => f.CuringCode == rightInfo.TCM_NO && f.CuringDir == rightInfo.TCM_DIR).FirstOrDefault();

                    var leftLocProduct = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).FirstOrDefault();

                    var leftStock = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).Count();

                    var rightLocProduct = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).FirstOrDefault();

                    var rightStock = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).Count();

                    var leftMaterialId = materialMsgs.Where(f => f.MaterialCode == leftInfo.TBM_SPEC).FirstOrDefault()?.Id ?? 0;
                    var rightMaterialId = materialMsgs.Where(f => f.MaterialCode == rightInfo.TBM_SPEC).FirstOrDefault()?.Id ?? 0;

                    var leftOccupyMsg = summaryTaskCount.Where(f => f.CuringCode == leftInfo.TCM_NO && f.CuringDir == leftInfo.TCM_DIR).FirstOrDefault();
                    var rightOccupyMsg = summaryTaskCount.Where(f => f.CuringCode == rightInfo.TCM_NO && f.CuringDir == rightInfo.TCM_DIR).FirstOrDefault();
                    WriteLog("创建出库订单5", true);
                    if (leftInfo.TBM_SPEC == rightInfo.TBM_SPEC && leftLocProduct is not null)
                    {
                        rightLocProduct = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0 && f.LocId != leftLocProduct.LocId).FirstOrDefault();

                        rightStock -= 1;
                    }

                    if (leftInfo.TBM_SPEC != rightInfo.TBM_SPEC)
                    {
                        var remark = $" 硫化机{leftInfo.TCM_NO}-左物料-{leftInfo.TBM_SPEC},右物料：{rightInfo.TBM_SPEC}不一致，暂不生成订单 | {DateTime.Now}";
                        continue;
                    }
                    if (leftInfo.TCM_HEIGHT != rightInfo.TCM_HEIGHT)
                    {
                        var remark = $" 硫化机{leftInfo.TCM_NO}-左物料-{leftInfo.TCM_HEIGHT},右物料：{rightInfo.TCM_HEIGHT} 高度不一致，暂不生成订单 | {DateTime.Now}";
                        continue;
                    }

                    #region 库存校验
                    //if (leftLocProduct is null || rightLocProduct is null)
                    //{
                    //    var leftNotEnableCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocEnable == 0).Count();
                    //    var leftTireLocCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.TireLoc == 1).Count();
                    //    var leftNotOutEnableCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 0).Count();
                    //    var leftTaskOccupyCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocTaskOccupy == 1).Count();

                    //    //var leftRemark = $"{leftInfo.TCM_NO}-{leftInfo.TCM_DIR} ,需要物料：{leftInfo.TBM_SPEC}，库存不足，需求数量：{GetInfoCount(leftInfo)},不可用数量：{leftNotEnableCount},锁定数量：{leftTireLocCount},不可出库数量：{leftNotOutEnableCount}，任务占用数量：{leftTaskOccupyCount} | {DateTime.Now}";
                    //    var leftRemark = $"{leftInfo.TCM_NO}-{leftInfo.TCM_DIR} ,需要物料：{leftInfo.TBM_SPEC}，库存不足， {DateTime.Now}";

                    //    manager.UpdateCuringRemark(leftCuringInfo?.EquipId ?? 0, leftRemark);

                    //    var rightNotEnableCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocEnable == 0).Count();
                    //    var rightTireLocCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.TireLoc == 1).Count();
                    //    var rightNotOutEnableCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocOutEnable == 0).Count();
                    //    var rightTaskOccupyCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocTaskOccupy == 1).Count();

                    //    //var rightRemark = $"{rightInfo.TCM_NO}-{rightInfo.TCM_DIR} ,需要物料：{rightInfo.TBM_SPEC}，库存不足，需求数量：{GetInfoCount(rightInfo)},不可用数量：{rightNotEnableCount}，锁定数量：{rightTireLocCount},不可出库数量：{rightNotOutEnableCount}，任务占用数量：{rightTaskOccupyCount} | {DateTime.Now}";
                    //    var rightRemark = $"{rightInfo.TCM_NO}-{rightInfo.TCM_DIR} ,需要物料：{rightInfo.TBM_SPEC}，库存不足， {DateTime.Now}";

                    //    manager.UpdateCuringRemark(rightCuringInfo?.EquipId ?? 0, rightRemark);

                    //    continue;
                    //}
                    #endregion

                    WriteLog("创建出库订单6", true);
                    if (leftMaterialId == 0 || rightMaterialId == 0)
                    {
                        continue;
                    }

                    if (leftMaterialId > 0 || rightMaterialId > 0)
                    {
                        //同步出库订单

                        WriteLog("创建出库订单-主表", true);
                        var master = manager.AddOutMasters((int)EnumCodeOutOrderType.RequesMaterial);//创建出库订单

                        WriteLog($"创建出库订单-主表{master.ToJson()}", true);
                        var leftadd = 0;
                        var rightadd = 0;
                        if (leftMaterialId > 0)
                        {
                            //更新物料表胎高  202507024 新增 
                            _ProdMaterial.UpdateMaterialHeightByCode(leftMaterialId.ToString(), leftInfo.TCM_HEIGHT);

                            leftadd = manager.AddOutOrderSummary(new POWmsOutOrderSummary
                            {
                                Id = XID.Nextval,
                                MasterId = master.Id,
                                //SummaryIndex = leftInfo.Priority,//设置为当时硫化机要胎的总数，越多，优先级越高
                                SummaryIndex = leftSummaryIndex,
                                TargetLoc = leftCuringInfo.LocId,
                                MaterialId = leftMaterialId,
                                Stock = leftStock,
                                RotateAngle = leftInfo.TCM_ANGLE,
                                TbmPs = leftInfo.TBM_PS,
                                CuringSpec = leftInfo.TBM_SPEC,
                                CuringSpecDesc = leftInfo.TBM_SPEC_DESC,
                                SkuBatch = $"硫化机{leftInfo.TCM_NO}-左物料-{leftInfo.TBM_SPEC},Curing:{leftInfo.REQ_GT_REQ}-Arm:{leftInfo.REQ_LD_GT}}}-CV:{leftInfo.REQ_CV_GT}-[orderCount:{(leftOccupyMsg?.SummaryCount ?? 0) + (leftOccupyMsg?.InCuringCount)}]",
                            });
                            WriteLog("创建出库订单-从表6", true);
                            //syncMesList.Add(new TcmInfo { TCM_NO = leftInfo.TCM_NO, TCM_DIR = leftInfo.TCM_DIR });
                            locProducts.Remove(leftLocProduct);
                        }
                        else
                        {
                            var remark = $" 硫化机-{curingCode}-{leftInfo.TCM_DIR},生产物料：{leftInfo.TBM_SPEC}不存在，该物料从未入库，暂不生成订单 | {DateTime.Now}";

                            manager.UpdateCuringRemark(leftOccupyMsg?.EquipId ?? 0, remark);
                        }

                        if (rightMaterialId > 0)
                        { //更新物料表胎高  202507024 新增 
                            _ProdMaterial.UpdateMaterialHeightByCode(rightMaterialId.ToString(), leftInfo.TCM_HEIGHT);
                            rightadd = manager.AddOutOrderSummary(new POWmsOutOrderSummary
                            {
                                Id = XID.Nextval,
                                MasterId = master.Id,
                                //SummaryIndex = rightInfo.Priority,//设置为当时硫化机要胎的总数，越多，优先级越高
                                SummaryIndex = rightSummaryIndex,
                                TargetLoc = rightCuringInfo.LocId,
                                MaterialId = rightMaterialId,
                                Stock = rightStock,
                                RotateAngle = rightInfo.TCM_ANGLE,
                                TbmPs = rightInfo.TBM_PS,
                                CuringSpec = rightInfo.TBM_SPEC,
                                CuringSpecDesc = rightInfo.TBM_SPEC_DESC,
                                SkuBatch = $" 硫化机{leftInfo.TCM_NO}-右物料：{rightInfo.TCM_HEIGHT} Curing:{rightInfo.REQ_GT_REQ}-Arm:{rightInfo.REQ_LD_GT}}}-CV:{rightInfo.REQ_CV_GT}-[orderCount:{(rightOccupyMsg?.SummaryCount ?? 0) + (rightOccupyMsg?.InCuringCount)}]",
                            });
                            WriteLog("创建出库订单-从表7", true);

                            //syncMesList.Add(new TcmInfo { TCM_NO = rightInfo.TCM_NO, TCM_DIR = rightInfo.TCM_DIR });


                            locProducts.Remove(rightLocProduct);
                        }

                        else
                        {
                            var remark = $" 硫化机-{curingCode}-{rightInfo.TCM_DIR},生产物料：{rightInfo.TBM_SPEC}不存在，该物料从未入库，暂不生成订单 | {DateTime.Now}";

                            manager.UpdateCuringRemark(leftOccupyMsg?.EquipId ?? 0, remark);
                        }

                        if (leftadd > 0)
                        {
                            //同步mes 修改请料状态
                            try
                            {
                                //WriteLog($"left请料成功,开始修改mes", true);
                                mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = leftInfo.TCM_NO, TCM_DIR = leftInfo.TCM_DIR });
                                WriteLog("创建出库订单- 修改请料状态left8", true);
                                //WriteLog($"left请料成功,完成修改mes", true);
                            }
                            catch (Exception ex)
                            {
                                //WriteLog($"left修改mes异常,{ex.ToString()}", true);
                            }
                        }
                        if (rightadd > 0)
                        {
                            //同步mes 修改请料状态
                            try
                            {
                                //WriteLog($"right请料成功,开始修改mes", true);
                                mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = rightInfo.TCM_NO, TCM_DIR = rightInfo.TCM_DIR });
                                WriteLog("创建出库订单- 修改请料状态right8", true);
                                //WriteLog($"right请料成功,完成修改mes", true);
                            }
                            catch (Exception ex)
                            {
                                //WriteLog($"right修改mes异常,{ex.ToString()}", true);
                            }
                        }




                        if (cacheDateTime.HasValue)
                        {
                            cache.TryRemove(curingCode, out _);
                        }
                    }
                }

            }


            //var res = manager.SaveChanges();

            //if (syncMesList.Any())
            //{
            //    //mesServices.UpdateSpecRcvFlag(syncMesList);
            //}
        }
        catch { }
        finally
        {
            //同步出库订单
            Task.Run(() => {
                try
                {
                    var bean = mesServices.GetAllOrderInfos();
                    if (bean == null) return;
                    foreach (var item in bean)
                    {
                        #region POTcmGtReq
                        Expression<Func<POTcmGtReq, bool>> whereExpression = x => true;
                        whereExpression = whereExpression.And(d => d.TcmNo == item.Req.TcmNo && d.TcmDir == item.Req.TcmDir);
                        var tcmGtReq = _tcmGtReqRepositories.First(whereExpression);
                        if (tcmGtReq is not null)
                        {
                            POTcmGtReq pOTcmGtReqnew = new POTcmGtReq()
                            {
                                ID= tcmGtReq.ID,
                                TcmNo = item.Req.TcmNo,
                                TcmDesc = item.Req.TcmDesc,
                                TcmDir = item.Req.TcmDir,
                                LdGt = item.Req.LdGt,
                                CvGt = item.Req.CvGt,
                                GtReq = item.Req.GtReq,
                                RegDt = item.Req.RegDt,
                                SulfopenTime = item.Req.SulfopenTime
                            };
                            Expression<Func<POTcmGtReq, bool>> whereTcmGtReqExpression = x => true;
                            whereTcmGtReqExpression = whereTcmGtReqExpression.And(d => d.ID == tcmGtReq.ID);
                            _tcmGtReqRepositories.Update(whereTcmGtReqExpression, pOTcmGtReqnew);
                        }
                        else
                        {
                            POTcmGtReq pOTcmGtReqnew = new POTcmGtReq()
                            {
                                ID = XID.Nextval,
                                TcmNo = item.Req.TcmNo,
                                TcmDesc = item.Req.TcmDesc,
                                TcmDir = item.Req.TcmDir,
                                LdGt = item.Req.LdGt,
                                CvGt = item.Req.CvGt,
                                GtReq = item.Req.GtReq,
                                RegDt = item.Req.RegDt,
                                SulfopenTime = item.Req.SulfopenTime

                            };
                            _tcmGtReqRepositories.Add(pOTcmGtReqnew);
                        }
                        #endregion

                        #region POTcmGtSpec
                        Expression<Func<POTcmGtSpec, bool>> whereTcmGtSpecExpression = x => true;
                        whereTcmGtSpecExpression = whereTcmGtSpecExpression.And(d => d.TcmNo == item.Req.TcmNo && d.TcmDir == item.Req.TcmDir);
                        var tcmGtSpec = _tcmGtSpecRepositories.First(whereTcmGtSpecExpression);
                        if (tcmGtSpec is not null)
                        {
                            POTcmGtSpec poTcmGtSpec = new POTcmGtSpec()
                            {
                                SPEC_ID= XID.Nextval,
                                TcmNo = item.Spec.TcmNo,
                                TcmDesc = item.Spec.TcmDesc,
                                TcmDir = item.Spec.TcmDir,
                                TcmSpec = item.Spec.TcmSpec,
                                TcmSpecDesc = item.Spec.TcmSpecDesc,
                                TbmSpec = item.Spec.TbmSpec,
                                TbmSpecDesc = item.Spec.TbmSpecDesc,
                                TbmSpecVer = item.Spec.TbmSpecVer,
                                TbmPs = item.Spec.TbmPs,
                                TcmAngle = item.Spec.TcmAngle,
                                RegDt = item.Spec.RegDt,
                                RcvFlag = item.Spec.RcvFlag,
                                TaskType = item.Spec.TaskType,
                                TcmHeight = item.Spec.TcmHeight,
                                Turnover = item.Spec.Turnover,
                                UPDATE = item.Spec.Update,
                            };
                            Expression<Func<POTcmGtSpec, bool>> wherePoTcmGtSpecExpression = x => true;
                            wherePoTcmGtSpecExpression = wherePoTcmGtSpecExpression.And(d => d.SPEC_ID == tcmGtSpec.SPEC_ID);
                            _tcmGtSpecRepositories.Update(wherePoTcmGtSpecExpression, poTcmGtSpec);
                        }
                        else
                        {
                            POTcmGtSpec poTcmGtSpec = new POTcmGtSpec()
                            {
                                SPEC_ID = XID.Nextval,
                                TcmNo = item.Spec.TcmNo,
                                TcmDesc = item.Spec.TcmDesc,
                                TcmDir = item.Spec.TcmDir,
                                TcmSpec = item.Spec.TcmSpec,
                                TcmSpecDesc = item.Spec.TcmSpecDesc,
                                TbmSpec = item.Spec.TbmSpec,
                                TbmSpecDesc = item.Spec.TbmSpecDesc,
                                TbmSpecVer = item.Spec.TbmSpecVer,
                                TbmPs = item.Spec.TbmPs,
                                TcmAngle = item.Spec.TcmAngle,
                                RegDt = item.Spec.RegDt,
                                RcvFlag = item.Spec.RcvFlag,
                                TaskType = item.Spec.TaskType,
                                TcmHeight = item.Spec.TcmHeight,
                                Turnover = item.Spec.Turnover,
                                UPDATE = item.Spec.Update,
                            };
                            _tcmGtSpecRepositories.Add(poTcmGtSpec);
                        }
                        #endregion
                    }
                }
                catch (Exception ex )
                {
                    WriteLog("同步硫化信息出错");
                }

            });
        }

    }

    //public void CreateOutSummariesV2()
    //{
    //    //return;

    //    var mesServices = K8.RSF.Client.Create<IMesService>();

    //    var tcmInfoTask = Task.Run(() => { return mesServices.GetAllInCuringInfos(); });
    //    //var tcmInfoTask = Task.Run(() => { return GetAllInCuringInfos(); });

    //    var summaryTaskCountsTask = Task.Run(() => { return _WmsOutOrderSummary.GetTaskSummaryOccupyCount(); });

    //    var SummaryOccupyTasks = Task.Run(() => { return _WmsOutOrderSummary.GetOccupySummarys(); });

    //    var locProductsTask = Task.Run(() => { return _ProdProduct.GetLocProductBeans(); });

    //    var tcmInfos = tcmInfoTask.Result;

    //    if (tcmInfos is null || !tcmInfos.Any())
    //    {
    //        //WriteLog("所有机台未请料", true);

    //        return;
    //    }

    //    var materialCodes = tcmInfos.Select(f => f.TBM_SPEC).ToList();

    //    var MaterialMsgsTask = Task.Run(() => { return _ProdMaterial.GetMaterialByCodes(materialCodes); });

    //    var summaryTaskCount = summaryTaskCountsTask.Result;

    //    //var locProducts = locProductsTask.Result;

    //    //if (locProducts is null || !locProducts.Any())
    //    //{
    //    //    //WriteLog($"库存不足，不生成订单", true);

    //    //    return;
    //    //}

    //    var summaryOccupy = SummaryOccupyTasks.Result;

    //    //if (summaryOccupy is not null && summaryOccupy.Any())
    //    //{
    //    //    var summaryStartLocs = summaryOccupy.Select(f => f.StartLoc).ToList();

    //    //    locProducts = locProducts.Where(f => !summaryStartLocs.Contains(f.LocId)).ToList();

    //    //    if (locProducts is null || !locProducts.Any())
    //    //    {
    //    //        //WriteLog($"库存不足，不生成订单,现有库存都已被订单占用。", true);

    //    //        return;
    //    //    }
    //    //}

    //    var manager = new SummaryManager();

    //    //List<TcmInfo> syncMesList = new List<TcmInfo>();

    //    foreach (var info in tcmInfos)
    //    {
    //        var OccupyMsg = summaryTaskCount.Where(f => f.CuringCode == info.TCM_NO && f.CuringDir == info.TCM_DIR).FirstOrDefault();

    //        if (info.REQ_GT_REQ == "X" || info.REQ_LD_GT == "X" || info.REQ_CV_GT == "X")
    //        {
    //            info.ActualRequireAmount = 0;

    //            var remark = $" {info.TCM_NO}-{info.TCM_DIR}硫化机/机械臂/存胎器有停用，硫化机是否停用：{info.REQ_GT_REQ == "X"} ,机械臂是否停用：{info.REQ_LD_GT == "X"}，存胎器是否停用：{info.REQ_CV_GT == "X"} | {DateTime.Now}";

    //            manager.UpdateCuringRemark(OccupyMsg?.EquipId ?? 0, remark);

    //            continue;
    //        }

    //        (info.ActualRequireAmount, info.Priority) = GetInfoCount(info);
    //        info.ActualRequireAmount = info.ActualRequireAmount - (OccupyMsg?.SummaryCount ?? 0) - (OccupyMsg?.InCuringCount ?? 0);

    //        //if (info.ActualRequireAmount <= 0)
    //        if (OccupyMsg?.SummaryCount + OccupyMsg?.InCuringCount > 0)
    //        {
    //            var remark = $" {info.TCM_NO}-{info.TCM_DIR}已生成指定数量的订单，需求数量：{GetInfoCount(info).count},订单数量：{OccupyMsg?.SummaryCount ?? 0},任务数量：{OccupyMsg?.InCuringCount} | {DateTime.Now}";

    //            if (info.RCV_FLAG == "N" && GetInfoCount(info).count > 0)
    //            {
    //                //syncMesList.Add(new TcmInfo { TCM_NO = info.TCM_NO, TCM_DIR = info.TCM_DIR });

    //                //mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = info.TCM_NO, TCM_DIR = info.TCM_DIR });
    //            }
    //            //如果是未生成任务的请料单 判断原物料跟现在物料是否一致
    //            if (OccupyMsg?.SummaryCount > 0 && OccupyMsg?.InCuringCount == 0)
    //            {
    //                //删除对应请料单
    //                //OccupyMsg.


    //            }
    //            manager.UpdateCuringRemark(OccupyMsg?.EquipId ?? 0, remark);

    //            continue;
    //        }
    //    }


    //    tcmInfos = tcmInfos.Where(f => f.ActualRequireAmount > 0).OrderBy(f => f.REQ_SULFOPEN_TIME).ToList();


    //    var materialMsgs = MaterialMsgsTask.Result;


    //    var curingCodes = tcmInfos.Select(f => f.TCM_NO).Distinct().ToList();

    //    foreach (var curingCode in curingCodes)
    //    {
    //        var curingTcmInfos = tcmInfos.Where(f => f.TCM_NO == curingCode && f.ActualRequireAmount > 0).ToList();

    //        if (curingTcmInfos is null || !curingTcmInfos.Any())
    //        {
    //            continue;
    //        }

    //        var curings = _RcsEquipCuring.GetEquipCuringsByCode(curingCode);

    //        if (curings is null || !curings.Any())
    //        {
    //            var remark = $" 未找到此硫化机-{curingCode}，或此硫化机-{curingCode}-已禁用 | {DateTime.Now}";

    //            //manager.UpdateCuringRemark(curingCode, remark);
    //            manager.UpdateCuringRemark2(curings.Select(f => f.Id).ToList(), remark);
    //            continue;
    //        }

    //        var direction = curings.FirstOrDefault()?.Direction;
    //        var leftSummaryIndex = 1;
    //        var rightSummaryIndex = 2;

    //        if (direction == ConstFields.DirectionN)
    //        {
    //            leftSummaryIndex = 2;
    //            rightSummaryIndex = 1;
    //        }



    //        var sendTime = curings.OrderByDescending(f => f.SendTime).FirstOrDefault()?.SendTime ?? DateTime.Now.AddMinutes(-1);

    //        //送胎后等待四秒后再生成
    //        var enableRequestTime = sendTime.AddSeconds(4);

    //        if (DateTime.Now < enableRequestTime)
    //        {
    //            var remark = $" 硫化机-{curingCode},刚刚送完，未到允许请料时间，允许请料时间：{enableRequestTime.ToString("yyyy-MM-dd HH:mm:ss.fff")} | {DateTime.Now}";

    //            manager.UpdateCuringRemark2(curings.Select(f => f.Id).ToList(), remark);
    //        }

    //        cache.TryGetValue(curingCode, out var cacheDateTime);

    //        //单模请料
    //        if (curingTcmInfos.Count() == 1)
    //        {
    //            continue;
    //            //单模请料直接退出
    //            //TODO暂时注释

    //            if (!cacheDateTime.HasValue)
    //            {
    //                cache.TryAdd(curingCode, DateTime.Now);

    //                continue;
    //            }

    //            //单模-等待十秒
    //            var endtime = ((DateTime)(cacheDateTime)).AddSeconds(30);


    //            if (endtime < DateTime.Now)
    //            {
    //                var curingTcmInfo = curingTcmInfos.FirstOrDefault();

    //                var curingInfo = summaryTaskCount.Where(f => f.CuringCode == curingTcmInfo.TCM_NO && f.CuringDir == curingTcmInfo.TCM_DIR).FirstOrDefault();


    //                //var locProduct = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).FirstOrDefault();

    //                var stock = 1;// locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).Count();

    //                //#region 库存校验
    //                //if (locProduct is null)
    //                //{
    //                //    var NotEnableCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocEnable == 0).Count();
    //                //    var tireLocCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.TireLoc == 1).Count();
    //                //    var NotOutEnableCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocOutEnable == 0).Count();
    //                //    var TaskOccupyCount = locProducts.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC && f.LocTaskOccupy == 1).Count();

    //                //    var remark = $"{curingTcmInfo.TCM_NO}-{curingTcmInfo.TCM_DIR} ,需要物料：{curingTcmInfo.TBM_SPEC}，库存不足，需求数量：{GetInfoCount(curingTcmInfo)},不可用数量：{NotEnableCount},锁定数量：{tireLocCount},不可出库数量：{NotOutEnableCount}，任务占用数量：{TaskOccupyCount} | {DateTime.Now}";

    //                //    manager.UpdateCuringRemark(curingInfo?.EquipId ?? 0, remark);

    //                //    continue;
    //                //}
    //                //#endregion

    //                var materialId = materialMsgs.Where(f => f.MaterialCode == curingTcmInfo.TBM_SPEC).FirstOrDefault()?.Id ?? 0;

    //                var occupyMsg = summaryTaskCount.Where(f => f.CuringCode == curingTcmInfo.TCM_NO && f.CuringDir == curingTcmInfo.TCM_DIR).FirstOrDefault();

    //                if (materialId <= 0)
    //                {
    //                    var remark = $" 硫化机-{curingCode}-{curingTcmInfo.TCM_DIR},生产物料：{curingTcmInfo.TBM_SPEC}不存在，该物料从未入库，暂不生成订单 | {DateTime.Now}";

    //                    manager.UpdateCuringRemark(occupyMsg?.EquipId ?? 0, remark);

    //                    continue;
    //                }

    //                var master = manager.AddOutMasters((int)EnumCodeOutOrderType.RequesMaterial);

    //                manager.AddOutOrderSummary(new POWmsOutOrderSummary
    //                {
    //                    Id = XID.Nextval,
    //                    MasterId = master.Id,
    //                    SummaryIndex = curingTcmInfo.Priority,//设置为当时硫化机要胎的总数，越多，优先级越高
    //                    TargetLoc = curingInfo.LocId,
    //                    MaterialId = materialId,
    //                    Stock = stock,
    //                    RotateAngle = curingTcmInfo.TCM_ANGLE,
    //                    TbmPs = curingTcmInfo.TBM_PS,
    //                    CuringSpec = curingTcmInfo.TBM_SPEC,
    //                    CuringSpecDesc = curingTcmInfo.TBM_SPEC_DESC,
    //                    SkuBatch = $"Curing:{curingTcmInfo.REQ_GT_REQ}-Arm:{curingTcmInfo.REQ_LD_GT}-CV:{curingTcmInfo.REQ_CV_GT}-[orderCount:{(occupyMsg?.SummaryCount ?? 0) + (occupyMsg?.InCuringCount)}]",
    //                });

    //                //syncMesList.Add(new TcmInfo { TCM_NO = curingTcmInfo.TCM_NO, TCM_DIR = curingTcmInfo.TCM_DIR });

    //                mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = curingTcmInfo.TCM_NO, TCM_DIR = curingTcmInfo.TCM_DIR });
    //                // locProducts.Remove(locProduct);

    //                try
    //                {
    //                    cache.TryRemove(curingCode, out _);
    //                }
    //                catch (Exception ex) { }
    //            }

    //            continue;
    //        }

    //        //双模请料
    //        if (curingTcmInfos.Count() == 2)
    //        {
    //            var leftInfo = curingTcmInfos.Where(f => f.TCM_NO == curingCode && f.TCM_DIR == "L").FirstOrDefault();
    //            var rightInfo = curingTcmInfos.Where(f => f.TCM_NO == curingCode && f.TCM_DIR == "R").FirstOrDefault();

    //            if (leftInfo is null || rightInfo is null)
    //            {
    //                continue;
    //            }

    //            var leftCuringInfo = summaryTaskCount.Where(f => f.CuringCode == leftInfo.TCM_NO && f.CuringDir == leftInfo.TCM_DIR).FirstOrDefault();
    //            var rightCuringInfo = summaryTaskCount.Where(f => f.CuringCode == rightInfo.TCM_NO && f.CuringDir == rightInfo.TCM_DIR).FirstOrDefault();

    //            //var leftLocProduct = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).FirstOrDefault();

    //            //var leftStock = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).Count();

    //            //var rightLocProduct = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).FirstOrDefault();

    //            //var rightStock = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0).Count();

    //            var leftMaterialId = materialMsgs.Where(f => f.MaterialCode == leftInfo.TBM_SPEC).FirstOrDefault()?.Id ?? 0;
    //            var rightMaterialId = materialMsgs.Where(f => f.MaterialCode == rightInfo.TBM_SPEC).FirstOrDefault()?.Id ?? 0;

    //            var leftOccupyMsg = summaryTaskCount.Where(f => f.CuringCode == leftInfo.TCM_NO && f.CuringDir == leftInfo.TCM_DIR).FirstOrDefault();
    //            var rightOccupyMsg = summaryTaskCount.Where(f => f.CuringCode == rightInfo.TCM_NO && f.CuringDir == rightInfo.TCM_DIR).FirstOrDefault();

    //            //if (leftInfo.TBM_SPEC == rightInfo.TBM_SPEC && leftLocProduct is not null)
    //            //{
    //            //    rightLocProduct = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 1 && f.LocTaskOccupy == 0 && f.LocEnable == 1 && f.TireLoc == 0 && f.LocId != leftLocProduct.LocId).FirstOrDefault();

    //            //    rightStock -= 1;
    //            //}

    //            //#region 库存校验
    //            //if (leftLocProduct is null || rightLocProduct is null)
    //            //{
    //            //    var leftNotEnableCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocEnable == 0).Count();
    //            //    var leftTireLocCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.TireLoc == 1).Count();
    //            //    var leftNotOutEnableCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocOutEnable == 0).Count();
    //            //    var leftTaskOccupyCount = locProducts.Where(f => f.MaterialCode == leftInfo.TBM_SPEC && f.LocTaskOccupy == 1).Count();

    //            //    var leftRemark = $"{leftInfo.TCM_NO}-{leftInfo.TCM_DIR} ,需要物料：{leftInfo.TBM_SPEC}，库存不足，需求数量：{GetInfoCount(leftInfo)},不可用数量：{leftNotEnableCount},锁定数量：{leftTireLocCount},不可出库数量：{leftNotOutEnableCount}，任务占用数量：{leftTaskOccupyCount} | {DateTime.Now}";

    //            //    manager.UpdateCuringRemark(leftCuringInfo?.EquipId ?? 0, leftRemark);

    //            //    var rightNotEnableCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocEnable == 0).Count();
    //            //    var rightTireLocCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.TireLoc == 1).Count();
    //            //    var rightNotOutEnableCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocOutEnable == 0).Count();
    //            //    var rightTaskOccupyCount = locProducts.Where(f => f.MaterialCode == rightInfo.TBM_SPEC && f.LocTaskOccupy == 1).Count();

    //            //    var rightRemark = $"{rightInfo.TCM_NO}-{rightInfo.TCM_DIR} ,需要物料：{rightInfo.TBM_SPEC}，库存不足，需求数量：{GetInfoCount(rightInfo)},不可用数量：{rightNotEnableCount}，锁定数量：{rightTireLocCount},不可出库数量：{rightNotOutEnableCount}，任务占用数量：{rightTaskOccupyCount} | {DateTime.Now}";

    //            //    manager.UpdateCuringRemark(rightCuringInfo?.EquipId ?? 0, rightRemark);

    //            //    continue;
    //            //}
    //            //#endregion


    //            if (leftMaterialId == 0 || rightMaterialId == 0)
    //            {
    //                continue;
    //            }

    //            if (leftMaterialId > 0 || rightMaterialId > 0)
    //            {
    //                var master = manager.AddOutMasters((int)EnumCodeOutOrderType.RequesMaterial);
    //                var leftadd = 0;
    //                var rightadd = 0;
    //                if (leftMaterialId > 0)
    //                {



    //                    leftadd = manager.AddOutOrderSummary(new POWmsOutOrderSummary
    //                    {
    //                        Id = XID.Nextval,
    //                        MasterId = master.Id,
    //                        //SummaryIndex = leftInfo.Priority,//设置为当时硫化机要胎的总数，越多，优先级越高
    //                        SummaryIndex = leftSummaryIndex,
    //                        TargetLoc = leftCuringInfo.LocId,
    //                        MaterialId = leftMaterialId,
    //                        Stock = 1,// leftStock,
    //                        RotateAngle = leftInfo.TCM_ANGLE,
    //                        TbmPs = leftInfo.TBM_PS,
    //                        CuringSpec = leftInfo.TBM_SPEC,
    //                        CuringSpecDesc = leftInfo.TBM_SPEC_DESC,
    //                        SkuBatch = $"Curing:{leftInfo.REQ_GT_REQ}-Arm:{leftInfo.REQ_LD_GT}}}-CV:{leftInfo.REQ_CV_GT}-[orderCount:{(leftOccupyMsg?.SummaryCount ?? 0) + (leftOccupyMsg?.InCuringCount)}]",
    //                    });

    //                    //syncMesList.Add(new TcmInfo { TCM_NO = leftInfo.TCM_NO, TCM_DIR = leftInfo.TCM_DIR });
    //                    //locProducts.Remove(leftLocProduct);
    //                }
    //                else
    //                {
    //                    var remark = $" 硫化机-{curingCode}-{leftInfo.TCM_DIR},生产物料：{leftInfo.TBM_SPEC}不存在，该物料从未入库，暂不生成订单 | {DateTime.Now}";

    //                    manager.UpdateCuringRemark(leftOccupyMsg?.EquipId ?? 0, remark);
    //                }

    //                if (rightMaterialId > 0)
    //                {
    //                    rightadd = manager.AddOutOrderSummary(new POWmsOutOrderSummary
    //                    {
    //                        Id = XID.Nextval,
    //                        MasterId = master.Id,
    //                        //SummaryIndex = rightInfo.Priority,//设置为当时硫化机要胎的总数，越多，优先级越高
    //                        SummaryIndex = rightSummaryIndex,
    //                        TargetLoc = rightCuringInfo.LocId,
    //                        MaterialId = rightMaterialId,
    //                        Stock = 1,// rightStock,
    //                        RotateAngle = rightInfo.TCM_ANGLE,
    //                        TbmPs = rightInfo.TBM_PS,
    //                        CuringSpec = rightInfo.TBM_SPEC,
    //                        CuringSpecDesc = rightInfo.TBM_SPEC_DESC,
    //                        SkuBatch = $"Curing:{rightInfo.REQ_GT_REQ}-Arm:{rightInfo.REQ_LD_GT}}}-CV:{rightInfo.REQ_CV_GT}-[orderCount:{(rightOccupyMsg?.SummaryCount ?? 0) + (rightOccupyMsg?.InCuringCount)}]",
    //                    });


    //                    //syncMesList.Add(new TcmInfo { TCM_NO = rightInfo.TCM_NO, TCM_DIR = rightInfo.TCM_DIR });


    //                    //locProducts.Remove(rightLocProduct);
    //                }

    //                else
    //                {
    //                    var remark = $" 硫化机-{curingCode}-{rightInfo.TCM_DIR},生产物料：{rightInfo.TBM_SPEC}不存在，该物料从未入库，暂不生成订单 | {DateTime.Now}";

    //                    manager.UpdateCuringRemark(leftOccupyMsg?.EquipId ?? 0, remark);
    //                }

    //                if (leftadd > 0)
    //                {
    //                    //同步mes 修改请料状态
    //                    try
    //                    {
    //                        //WriteLog($"left请料成功,开始修改mes", true);
    //                        mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = leftInfo.TCM_NO, TCM_DIR = leftInfo.TCM_DIR });
    //                        //WriteLog($"left请料成功,完成修改mes", true);
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        //WriteLog($"left修改mes异常,{ex.ToString()}", true);
    //                    }
    //                }
    //                if (rightadd > 0)
    //                {
    //                    //同步mes 修改请料状态
    //                    try
    //                    {
    //                        //WriteLog($"right请料成功,开始修改mes", true);
    //                        mesServices.UpdateSpecRcvFlag(new TcmInfo { TCM_NO = rightInfo.TCM_NO, TCM_DIR = rightInfo.TCM_DIR });
    //                        //WriteLog($"right请料成功,完成修改mes", true);
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        //WriteLog($"right修改mes异常,{ex.ToString()}", true);
    //                    }
    //                }




    //                if (cacheDateTime.HasValue)
    //                {
    //                    cache.TryRemove(curingCode, out _);
    //                }
    //            }
    //        }

    //    }


    //    //var res = manager.SaveChanges();

    //    //if (syncMesList.Any())
    //    //{
    //    //    //mesServices.UpdateSpecRcvFlag(syncMesList);
    //    //}

    //}

    //public int UpdateSpecRcvFlag(TcmInfo tcminfo)
    //{
    //    var db = Db.Default;
    //    var tcmSpec = db.TcmGtSpecs.FirstOrDefault(f => f.TcmNo == tcminfo.TCM_NO && f.TcmDir == tcminfo.TCM_DIR);

    //    if (tcmSpec is not null)
    //    {
    //        tcmSpec.RcvFlag = "Y";
    //    }
    //    return db.SaveChanges();
    //}
    private static (int count, int priority) GetInfoCount(TcmInfo tcmInfo)
    {
        int count = 0;
        int priority = 0;
        var tcmNo = tcmInfo.TCM_NO;
        if (tcmInfo.REQ_GT_REQ == "Y" && tcmInfo.RCV_FLAG == "N")
        {
            //count += 1;

            //if (tcmInfo.REQ_LD_GT == "N")
            //{
            //    //if (tcmNo.Contains($"02K33") || tcmNo.Contains("02K34"))
            //    //{
            //    count += 1;
            //    //}
            //    priority += 1;
            //}
            if (tcmInfo.REQ_CV_GT == "N")
            {
                count += 1;
                priority += 1;
            }
        }


        return (count, priority);
    }

    //public List<TcmInfo> GetAllInCuringInfos()
    //{
    //    var db = Db.Default;

    //    var reqAndSpecs = (from req in db.TcmGtReqs
    //                       join spec in db.TcmGtSpecs on new { req.TcmNo, req.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
    //                       where (req.GtReq == "Y" || req.LdGt == "N" || req.CvGt == "N")
    //                       orderby req.RegDt
    //                       select new
    //                       {
    //                           Req = req,
    //                           Spec = spec,
    //                       }).ToList();

    //    var reqAndSpecs1 = db.TcmGtReqs.Join(db.TcmGtSpecs, f => new { f.TcmNo, f.TcmDir }, s => new { s.TcmNo, s.TcmDir }, (f, s) => new
    //    {

    //        Req = f,
    //        Spec = s,
    //    }).Where(t => t.Req.GtReq == "Y" || t.Req.LdGt == "N" || t.Req.CvGt == "N").ToQueryString(); 
    //     //reqAndSpecs1

    //    List<TcmInfo> infos = new List<TcmInfo>();

    //    foreach (var reqAndSpec in reqAndSpecs)
    //    {
    //        infos.Add(TcmInfo.Create(reqAndSpec.Spec, reqAndSpec.Req));
    //    }


    //    return infos.OrderBy(f => f.REQ_REG_DT).ToList();
    //}

    // public class TcmInfo
    // {
    //     public string TCM_NO { get; set; }
    //     public string TCM_DIR { get; set; }
    //     public string TCM_DESC { get; set; }
    //     public string TCM_SPEC { get; set; }
    //     public string TCM_SPEC_DESC { get; set; }
    //     public string TBM_SPEC { get; set; }
    //     public string TBM_SPEC_DESC { get; set; }
    //     public string TBM_SPEC_VER { get; set; }
    //     public string TBM_PS { get; set; }
    //     public int TCM_ANGLE { get; set; }
    //     public string TCM_HEIGHT { get; set; }
    //     public DateTime REG_DT { get; set; }
    //     public string RCV_FLAG { get; set; }
    //     public string TASK_TYPE { get; set; }
    //     public string TURNOVER { get; set; }
    //     public string TASKCODE { get; set; }
    //     public string EXEC_RESULT { get; set; }

    //     public string REQ_LD_GT { get; set; }
    //     public string REQ_CV_GT { get; set; }
    //     public string REQ_GT_REQ { get; set; }
    //     public DateTime REQ_REG_DT { get; set; }
    //     public DateTime? REQ_SULFOPEN_TIME { get; set; }

    //     public string OrderMsg { get; set; }

    //     /// <summary>
    //     /// 实际所需要胎的数量（计划要胎的数量 - 在途胎数量 - 订单数量）
    //     /// </summary>
    //     public int ActualRequireAmount { get; set; }
    //     public int Priority { get; set; }

    //     public static TcmInfo Create(POTcmGtSpec spec, POTcmGtReq req)
    //     {
    //         return new TcmInfo()
    //         {
    //             TCM_NO = spec.TcmNo,
    //             TCM_DIR = spec.TcmDir,
    //             TCM_DESC = spec.TcmDesc,
    //             TCM_SPEC = spec.TcmSpec,
    //             TCM_SPEC_DESC = spec.TcmSpecDesc,
    //             TCM_ANGLE = Convert.ToInt32(spec?.TcmAngle ?? 0),
    //             TCM_HEIGHT = spec.TcmHeight,
    //             TBM_SPEC = spec.TbmSpec,
    //             TBM_SPEC_DESC = spec.TbmSpecDesc,
    //             TBM_PS = spec.TbmPs,
    //             TBM_SPEC_VER = spec.TbmSpecVer,
    //             REQ_REG_DT = spec.RegDt.Value,
    //             RCV_FLAG = spec.RcvFlag,
    //             TASK_TYPE = spec.TaskType,
    //             TURNOVER = spec.Turnover,
    //             //TASKCODE = spec.TASKCODE,
    //             //EXEC_RESULT = spec.EXECRESULT,
    //             REQ_LD_GT = req.LdGt,
    //             REQ_CV_GT = req.CvGt,
    //             REQ_GT_REQ = req.GtReq,
    //             REG_DT = req.RegDt.Value,
    //             REQ_SULFOPEN_TIME = req.SulfopenTime,
    //             OrderMsg = $"{req.CvGt}-{req.LdGt}-{req.GtReq}"
    //         };
    //     }
    // }

}




